From 8151c07d59deeeb013e7dde6d3da6bc481fc7321 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Fri, 27 Nov 2026 17:56:48 +0800 Subject: [PATCH 01/13] feat(auth): add Aliyun OAuth login with pre-release control-plane isolation - add `bl auth --login aliyun` PKCE loopback flow (/oauth/callback), token -> STS exchange (PascalCase/camelCase compatible) -> GenerateCLIAccessToken -> loginInfo, with three-branch auto renewal - store OAuth sessions as private plaintext files (0600 + atomic write, Windows private ACL) instead of OS keychain, aligned with aliyun-cli - add BAILIAN_PRE control-plane switch: isolated pre/control-pre.json profiles with control_environment guard, verified pre endpoints for OAuth/OpenAPI, and hard blocks for unverified management routes --- README.md | 33 +- README.zh.md | 33 +- docs/agents/auth-change.md | 13 + packages/cli/README.md | 33 +- packages/cli/README.zh.md | 33 +- packages/cli/src/commands.ts | 49 + packages/cli/src/main.ts | 11 +- packages/commands/src/commands/auth/aliyun.ts | 684 ++++++++ .../commands/src/commands/auth/console-ui.ts | 74 +- .../commands/auth/generate-access-token.ts | 70 +- .../src/commands/auth/login-console.ts | 110 +- packages/commands/src/commands/auth/login.ts | 141 +- packages/commands/src/commands/auth/logout.ts | 99 +- packages/commands/src/commands/auth/status.ts | 92 +- .../commands/src/commands/config/ui-html.ts | 2 +- .../commands/src/commands/config/ui-i18n.ts | 4 +- packages/commands/src/commands/config/ui.ts | 29 +- .../commands/src/commands/finetune/fee.ts | 2 +- .../src/commands/token-plan/add-member.ts | 3 +- .../src/commands/token-plan/assign-seats.ts | 3 +- .../src/commands/token-plan/create-key.ts | 3 +- .../src/commands/token-plan/list-seats.ts | 3 +- .../commands/src/commands/token-plan/utils.ts | 10 +- .../commands/src/commands/workspace/init.ts | 104 +- packages/commands/src/index.ts | 1 + packages/commands/tests/auth-aliyun.test.ts | 1012 +++++++++++ packages/commands/tests/e2e/auth.e2e.test.ts | 57 + packages/commands/tests/e2e/topic-routes.ts | 1 + ...atalog-workspace-permission-output.test.ts | 28 +- .../tests/output/local-command-output.test.ts | 9 + packages/core/src/auth/aliyun-config.ts | 110 ++ packages/core/src/auth/aliyun-oauth.ts | 308 ++++ packages/core/src/auth/aliyun-types.ts | 53 + packages/core/src/auth/index.ts | 31 + packages/core/src/auth/openapi-provider.ts | 482 ++++++ packages/core/src/auth/refresh-token.ts | 113 +- packages/core/src/auth/resolver.ts | 12 + packages/core/src/auth/secure-store.ts | 240 +++ packages/core/src/auth/store.ts | 208 ++- packages/core/src/auth/types.ts | 12 + packages/core/src/client/bailian-control.ts | 16 +- packages/core/src/client/client.ts | 52 +- packages/core/src/client/console-session.ts | 91 +- packages/core/src/config/control-plane.ts | 105 ++ packages/core/src/config/index.ts | 19 +- packages/core/src/config/loader.ts | 245 ++- packages/core/src/config/paths.ts | 17 +- packages/core/src/config/schema.ts | 8 + packages/core/src/config/store.ts | 48 +- packages/core/src/console/gateway.ts | 56 +- packages/core/src/console/index.ts | 1 + packages/core/src/errors/credential.ts | 6 +- packages/core/src/utils/file-lock.ts | 81 + packages/core/tests/aliyun-oauth.test.ts | 529 ++++++ .../core/tests/oauth-secure-store.test.ts | 289 ++++ packages/core/tests/openapi-provider.test.ts | 1512 +++++++++++++++++ packages/runtime/src/create-cli.ts | 156 +- packages/runtime/src/error-handler.ts | 35 +- packages/runtime/src/middleware.ts | 158 +- .../runtime/tests/console-aksk-auth.test.ts | 167 +- skills/bailian-cli/reference/auth.md | 103 +- skills/bailian-cli/reference/index.md | 7 +- skills/bailian-cli/reference/workspace.md | 28 +- 63 files changed, 7498 insertions(+), 546 deletions(-) create mode 100644 packages/commands/src/commands/auth/aliyun.ts create mode 100644 packages/commands/tests/auth-aliyun.test.ts create mode 100644 packages/core/src/auth/aliyun-config.ts create mode 100644 packages/core/src/auth/aliyun-oauth.ts create mode 100644 packages/core/src/auth/aliyun-types.ts create mode 100644 packages/core/src/auth/openapi-provider.ts create mode 100644 packages/core/src/auth/secure-store.ts create mode 100644 packages/core/src/config/control-plane.ts create mode 100644 packages/core/src/utils/file-lock.ts create mode 100644 packages/core/tests/aliyun-oauth.test.ts create mode 100644 packages/core/tests/oauth-secure-store.test.ts create mode 100644 packages/core/tests/openapi-provider.test.ts diff --git a/README.md b/README.md index 29649b765..a84e5b69a 100644 --- a/README.md +++ b/README.md @@ -190,9 +190,36 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ## Authentication -### Console Login (OAuth, Recommended) +### Aliyun OAuth -Required for console capability commands (model list, flow-agent list, MCP list, workspace, usage queries, rate-limit increases, direct console calls). It can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console`; use the API Key login below. +`bl auth --login aliyun` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. For a first online login, provide the confirmed production application ID and authorization URL: + +```bash +bl auth --login aliyun --config aliyun \ + --client-id \ + --authorization-url +``` + +Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. + +Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--no-browser` prints the URL and still waits for a callback on the same machine. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. + +#### Domestic pre-release control plane + +Set `BAILIAN_PRE=1` (or `true`) to select the domestic `cn-beijing` control plane. Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. + +```bash +BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth status +``` + +Supported OAuth and OpenAPI routes are selected automatically. Confirm the pre-release CLI gateway protocol before supplying `BAILIAN_PRE_CONSOLE_GATEWAY`. Native Console browser login also requires a confirmed login and callback origin via `BAILIAN_PRE_CONSOLE_ORIGIN`. The CLI does not change hosts or proxy configuration. Unsupported regions and management services do not fall back to online endpoints. + +Aliyun OAuth credentials are stored as **plaintext** in a separate `oauth/.json` file under the CLI config directory, not in the main config. Writes are atomic; the cache directory and files use `0700` and `0600` on Unix, and Windows requires private ACLs. No Keychain or system credential service is used. Keep this directory private and out of shared backups. Sign in again if you used the previous encrypted format; it is not migrated. OAuth refresh and STS renewal are shared across Console and OpenAPI calls. `auth status` only describes configured credentials; it does not validate or refresh them. Full `auth logout` or `auth logout --aliyun` revokes the RT; partial `--console`/`--open-api` logout disables only that domain. OAuth login preserves existing API keys and does not provision inference keys, initialize workspaces, modify hosts/proxies, or activate paid services. + +### Console Browser Login (Recommended) + +Console capability commands (model list, flow-agent list, MCP list, workspace, usage queries, rate-limit increases, direct console calls) can use this browser login or Aliyun OAuth above. Browser login can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console` for inference; use the API Key login below. ```bash bl auth login --console @@ -228,7 +255,7 @@ 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 and member management requires OpenAPI credentials: an Alibaba Cloud AccessKey/STS pair or an Aliyun OAuth session. Get yours from the [RAM Console](https://ram.console.aliyun.com/manage/ak). > Recommended: create a RAM sub-account with minimum privileges instead of using the root account's AK/SK. diff --git a/README.zh.md b/README.zh.md index de80a6354..cadaee8f2 100644 --- a/README.zh.md +++ b/README.zh.md @@ -189,9 +189,36 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ## 认证方式 -### 控制台登录(OAuth,推荐) +### 阿里云 OAuth -控制台能力命令(模型列表、应用列表、MCP 列表、工作空间、用量查询、限流提额、控制台直调)需要使用此登录方式,并可在需要时创建普通 API Key。Token Plan 等订阅计划不能使用 `--console`,请使用下面的 API Key 登录方式。 +`bl auth --login aliyun` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。首次在线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: + +```bash +bl auth --login aliyun --config aliyun \ + --client-id <正式应用ID> \ + --authorization-url <已确认的授权地址> +``` + +IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 + +线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--no-browser` 只禁止自动打开浏览器,仍等待同一台机器的本机回调;`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 + +#### 国内预发控制面 + +用 `BAILIAN_PRE=1`(也接受 `true`)切换国内 `cn-beijing` 控制面;未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 + +```bash +BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth status +``` + +预发 OAuth 和已支持的 OpenAPI 端点自动选择。启用 Console 调用前,须确认预发 CLI 网关协议并设置 `BAILIAN_PRE_CONSOLE_GATEWAY`;使用原生浏览器登录还须确认登录页和回调可信源,并设置 `BAILIAN_PRE_CONSOLE_ORIGIN`。CLI 不改变 hosts/代理。未经确认的地域和管理服务不会自动改走线上。 + +阿里云 OAuth 凭据以**明文**存放在配置目录下独立的 `oauth/.json` 中,不写入主配置。文件采用原子写入;Unix 上目录和文件分别为 `0700` 和 `0600`,Windows 要求私有 ACL。不使用钥匙串或系统凭据服务,请勿共享或备份到不受保护的位置。旧加密会话不迁移,需要重新登录。Console 与 OpenAPI 共享 OAuth/STS 续期。`auth status` 仅展示当前配置,不在线验证或刷新;完整 `auth logout` 或 `auth logout --aliyun` 会撤销 RT,部分 `--console`/`--open-api` 退出仅停用对应域。OAuth 登录保留已有模型 API Key,不创建推理密钥、不初始化工作空间、不改 hosts/代理,也不自动开通付费服务。 + +### 控制台浏览器登录(推荐) + +控制台能力命令(模型列表、应用列表、MCP 列表、工作空间、用量查询、限流提额、控制台直调)可使用此浏览器登录或上面的阿里云 OAuth。浏览器登录可在需要时创建普通 API Key。Token Plan 等订阅计划推理不能使用 `--console`,请使用下面的 API Key 登录方式。 ```bash bl auth login --console @@ -227,7 +254,7 @@ bl auth login --api-key ### 阿里云 OpenAPI AK/SK -Token Plan 的席位与成员管理需要阿里云 AccessKey。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。 +Token Plan 的席位与成员管理需要 OpenAPI 凭据,可使用阿里云 AccessKey/STS 或阿里云 OAuth 会话。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。 > 建议:创建 RAM 子账号并授予最小权限,避免使用主账号 AK/SK。 diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index 99cea7cad..1a5fae14f 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -70,6 +70,19 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - `--console --token-stdin` 与 `--no-browser` 互斥,必须显式指定 `--console-region`;只接受非 TTY stdin 的单个原始 token(最多 64 KiB),拒绝空输入、JSON、Bearer 前缀及多 token 输入。此分支不启动浏览器或回调服务,经目标网关 `loginInfo` 验证成功才保存 token/site/region 并激活指定 Profile;保留其他凭证,失败和 dry-run 不写入、不激活,dry-run 不读取 stdin。 - PNA 响应头只是兼容措施,不能宣称绕过 Chrome LNA 权限或 Safari 混合内容限制。回归覆盖真实 loopback 请求、超时、浏览器启动竞态、stdin 失败不改配置及输出不泄漏 token。 +### 阿里云 OAuth 登录与续期 + +- `bl auth --login aliyun` 是可执行的 `auth` 父命令,保留既有 `auth login/status/logout` 子命令;不在 runtime 改写 argv。 +- OAuth 回调仅监听 `127.0.0.1` 随机端口的 `/oauth/callback` 路径,授权请求与换票使用同一 `redirect_uri`。IAM 登记 `http://127.0.0.1:12345/oauth/callback`;NativeApp 忽略回环端口,但协议、主机和路径必须一致,不保留根路径兼容。 +- 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile;端点维持显式参数 > Profile > 默认地址。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和已确认的国内端点,不读线上控制面凭据、不隐式回退、不改 hosts/代理。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的管理接口必须联网前阻断。模型域来源和 `kscli` 不受开关影响。 +- `aliyun_oauth` 仅保存端点、client_id/scope、会话引用、域激活状态及到期元数据;OAuth AT 不覆盖旧的 Console `access_token`。凭据存于配置目录下独立的 `oauth/.json` 明文文件,绑定会话引用,不写入主配置。Unix 校验目录 `0700` 和文件 `0600` 及所有者,Windows 校验私有 ACL;拒绝非普通文件及链接,使用同目录唯一临时文件、fsync 和原子替换。旧加密会话不迁移,需要重新登录。 +- 同一个异步 OpenAPI provider 负责 OAuth AT/RT→STS,Console 换票与 OpenAPI 签名前复用。优先级保持 flag > 百炼 env > 所选 file(静态或 OAuth)> 阿里云 env;临时来源不落盘。`describe/stored` 只读元数据,不读取凭据文件;静态 dry-run 不调用 OAuth,框架更新/遥测仍遵循原设置。 +- `/v1/exchange` 接受完整的 PascalCase 或 camelCase STS 字段,不跨两套字段拼接。两种格式均校验非空字符串凭据及未来到期时间,不输出原始响应体。 +- RT 刷新开始前保存 pending 状态;新 RT 必须安全持久化后才能继续 STS/业务请求。刷新结果不确定时不重放旧 RT;没有返回新 RT 时保留旧值。会话锁跨进程协调,配置写入使用文件锁、唯一临时文件与原子替换。 +- 会话文件绑定端点/client/scope 指纹,公开元数据被改动时须重新登录,不能把旧 RT 发往新端点;Console 缓存按 gateway/region/site/switchAgent 隔离。Console token 仍保持原业务请求成功后才保存的规则。 +- `workspace init` 是 OpenAPI 与 Console 混合命令,以 `auth: "openapi"` 校验主凭据,两类调用均经过同一个 Client;纯 Console Gateway 命令仍声明 `auth: "console"`。`auth generate-access-token` 也复用所选 OpenAPI 凭据,不再要求手工重复输入已登录的凭据。 +- 完整退出或 `--aliyun` 撤销 RT 并删除安全缓存;部分 `--console`/`--open-api` 仅停用对应域。删除有 OAuth 会话的 Profile 前必须先退出 OAuth,避免遗留无法撤销的安全缓存。重新登录替换本地引用,不把本地替换描述为服务端旧授权已撤销。 + ### Console token 签发与刷新 - `packages/core/src/client/console-session.ts` 集中管理 Console 凭证、换票、重试、并发协调及落盘;`Client.console()` 委托给该内部模块,对外调用方式不变。 diff --git a/packages/cli/README.md b/packages/cli/README.md index 29649b765..a84e5b69a 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -190,9 +190,36 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ## Authentication -### Console Login (OAuth, Recommended) +### Aliyun OAuth -Required for console capability commands (model list, flow-agent list, MCP list, workspace, usage queries, rate-limit increases, direct console calls). It can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console`; use the API Key login below. +`bl auth --login aliyun` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. For a first online login, provide the confirmed production application ID and authorization URL: + +```bash +bl auth --login aliyun --config aliyun \ + --client-id \ + --authorization-url +``` + +Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. + +Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--no-browser` prints the URL and still waits for a callback on the same machine. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. + +#### Domestic pre-release control plane + +Set `BAILIAN_PRE=1` (or `true`) to select the domestic `cn-beijing` control plane. Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. + +```bash +BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth status +``` + +Supported OAuth and OpenAPI routes are selected automatically. Confirm the pre-release CLI gateway protocol before supplying `BAILIAN_PRE_CONSOLE_GATEWAY`. Native Console browser login also requires a confirmed login and callback origin via `BAILIAN_PRE_CONSOLE_ORIGIN`. The CLI does not change hosts or proxy configuration. Unsupported regions and management services do not fall back to online endpoints. + +Aliyun OAuth credentials are stored as **plaintext** in a separate `oauth/.json` file under the CLI config directory, not in the main config. Writes are atomic; the cache directory and files use `0700` and `0600` on Unix, and Windows requires private ACLs. No Keychain or system credential service is used. Keep this directory private and out of shared backups. Sign in again if you used the previous encrypted format; it is not migrated. OAuth refresh and STS renewal are shared across Console and OpenAPI calls. `auth status` only describes configured credentials; it does not validate or refresh them. Full `auth logout` or `auth logout --aliyun` revokes the RT; partial `--console`/`--open-api` logout disables only that domain. OAuth login preserves existing API keys and does not provision inference keys, initialize workspaces, modify hosts/proxies, or activate paid services. + +### Console Browser Login (Recommended) + +Console capability commands (model list, flow-agent list, MCP list, workspace, usage queries, rate-limit increases, direct console calls) can use this browser login or Aliyun OAuth above. Browser login can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console` for inference; use the API Key login below. ```bash bl auth login --console @@ -228,7 +255,7 @@ 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 and member management requires OpenAPI credentials: an Alibaba Cloud AccessKey/STS pair or an Aliyun OAuth session. Get yours from the [RAM Console](https://ram.console.aliyun.com/manage/ak). > Recommended: create a RAM sub-account with minimum privileges instead of using the root account's AK/SK. diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index de80a6354..cadaee8f2 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -189,9 +189,36 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ## 认证方式 -### 控制台登录(OAuth,推荐) +### 阿里云 OAuth -控制台能力命令(模型列表、应用列表、MCP 列表、工作空间、用量查询、限流提额、控制台直调)需要使用此登录方式,并可在需要时创建普通 API Key。Token Plan 等订阅计划不能使用 `--console`,请使用下面的 API Key 登录方式。 +`bl auth --login aliyun` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。首次在线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: + +```bash +bl auth --login aliyun --config aliyun \ + --client-id <正式应用ID> \ + --authorization-url <已确认的授权地址> +``` + +IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 + +线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--no-browser` 只禁止自动打开浏览器,仍等待同一台机器的本机回调;`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 + +#### 国内预发控制面 + +用 `BAILIAN_PRE=1`(也接受 `true`)切换国内 `cn-beijing` 控制面;未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 + +```bash +BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth status +``` + +预发 OAuth 和已支持的 OpenAPI 端点自动选择。启用 Console 调用前,须确认预发 CLI 网关协议并设置 `BAILIAN_PRE_CONSOLE_GATEWAY`;使用原生浏览器登录还须确认登录页和回调可信源,并设置 `BAILIAN_PRE_CONSOLE_ORIGIN`。CLI 不改变 hosts/代理。未经确认的地域和管理服务不会自动改走线上。 + +阿里云 OAuth 凭据以**明文**存放在配置目录下独立的 `oauth/.json` 中,不写入主配置。文件采用原子写入;Unix 上目录和文件分别为 `0700` 和 `0600`,Windows 要求私有 ACL。不使用钥匙串或系统凭据服务,请勿共享或备份到不受保护的位置。旧加密会话不迁移,需要重新登录。Console 与 OpenAPI 共享 OAuth/STS 续期。`auth status` 仅展示当前配置,不在线验证或刷新;完整 `auth logout` 或 `auth logout --aliyun` 会撤销 RT,部分 `--console`/`--open-api` 退出仅停用对应域。OAuth 登录保留已有模型 API Key,不创建推理密钥、不初始化工作空间、不改 hosts/代理,也不自动开通付费服务。 + +### 控制台浏览器登录(推荐) + +控制台能力命令(模型列表、应用列表、MCP 列表、工作空间、用量查询、限流提额、控制台直调)可使用此浏览器登录或上面的阿里云 OAuth。浏览器登录可在需要时创建普通 API Key。Token Plan 等订阅计划推理不能使用 `--console`,请使用下面的 API Key 登录方式。 ```bash bl auth login --console @@ -227,7 +254,7 @@ bl auth login --api-key ### 阿里云 OpenAPI AK/SK -Token Plan 的席位与成员管理需要阿里云 AccessKey。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。 +Token Plan 的席位与成员管理需要 OpenAPI 凭据,可使用阿里云 AccessKey/STS 或阿里云 OAuth 会话。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。 > 建议:创建 RAM 子账号并授予最小权限,避免使用主账号 AK/SK。 diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 2a4438bb9..9d07fae5f 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -1,6 +1,7 @@ import type { AnyCommand } from "bailian-cli-core"; import { deprecatedCommand } from "./deprecated.ts"; import { + authRoot, authLogin, authStatus, authLogout, @@ -400,6 +401,7 @@ import { // (no side effects) so tools like generate-reference.ts can import it without // starting the CLI. export const commands: Record = { + auth: authRoot, "auth login": authLogin, "auth status": authStatus, "auth logout": authLogout, @@ -808,3 +810,50 @@ export const commandAliases: Record = { // Pre-migration name of "quota update". "quota request": quotaUpdate, }; + +const unsupportedPreGroups = new Set([ + "agents", + "batch", + "cmodel", + "dataset", + "deploy", + "finetune", + "knowledge", + "managed-agent", + "memory", + "permission", + "quota", + "sandbox", +]); +const preModelOrLocalCommands = new Set([ + "batch convert", + "cmodel base-models", + "dataset generate", + "dataset split", + "dataset validate", + "finetune capability", + "finetune params", + "finetune price", + "finetune train-options", + "knowledge chat", + "knowledge search", + "managed-agent init", + "managed-agent validate", + "managed-agent project init", + "managed-agent project validate", + "managed-agent state list", + "managed-agent state rm", + "managed-agent state show", +]); + +export function hasUnverifiedPreControlPlaneRoute(path: string): boolean { + const command = commands[path] ?? commandAliases[path]; + if (!command || preModelOrLocalCommands.has(path)) return false; + const [group, subgroup, operation] = path.split(" "); + if (group === "managed-agent") return true; + if (command.auth === "console" || command.auth === "openapi") return false; + if (group === "speech") { + return subgroup === "vocabulary" || (subgroup === "voice" && operation !== "preview"); + } + return unsupportedPreGroups.has(group!); +} diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index ea836fc29..6199a01eb 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -1,5 +1,6 @@ import { createCli } from "bailian-cli-runtime"; -import { commandAliases, commands } from "./commands.ts"; +import { resolvePreControlPlane, UsageError } from "bailian-cli-core"; +import { commandAliases, commands, hasUnverifiedPreControlPlaneRoute } from "./commands.ts"; import { commandPackPolicy } from "./command-pack-policy.ts"; import pkg from "../package.json" with { type: "json" }; import { resolveAliyunIntegration } from "./integrations/aliyun.ts"; @@ -22,5 +23,13 @@ void createCli( npmPackage: "bailian-cli", quickStartTasks, commandPacks: commandPackPolicy, + preControlPlane: () => resolvePreControlPlane(process.env), + validatePreControlPlaneCommand: (path) => { + if (hasUnverifiedPreControlPlaneRoute(path)) { + throw new UsageError( + "This command has no verified pre-release control-plane route. / 此命令没有已确认的预发控制面路由。", + ); + } + }, }, ).run(); diff --git a/packages/commands/src/commands/auth/aliyun.ts b/packages/commands/src/commands/auth/aliyun.ts new file mode 100644 index 000000000..1ccd3b116 --- /dev/null +++ b/packages/commands/src/commands/auth/aliyun.ts @@ -0,0 +1,684 @@ +import http from "node:http"; +import { + ALIYUN_CLI_CLIENT_ID, + ALIYUN_CLI_SCOPE, + ALIYUN_OAUTH_BASE_URL, + BailianError, + ExitCode, + PRE_ALIYUN_AUTHORIZATION_URL, + PRE_ALIYUN_OAUTH_BASE_URL, + PRE_BAILIAN_CONTROL_HOST, + PRE_MODEL_STUDIO_HOST, + UsageError, + aliyunAuthorizationUrl, + consoleCredentialKey, + createOAuthProofKey, + defineCommand, + exchangeAliyunCode, + exchangeAliyunSts, + generateCLIAccessToken, + normalizeOAuthUrl, + normalizeOpenApiHost, + parseAliyunCallback, + requirePreConsoleGateway, + resolveConsoleGatewayOrigin, + resolveModelStudioHost, + revokeAliyunTokens, + validateConsoleAccessToken, + type AliyunOAuthProfile, + type AliyunOAuthSession, + type AuthStore, + type CommandOutput, + type Identity, + type LocalizedText, + type Settings, +} from "bailian-cli-core"; +import { listenLocalServer, openInBrowser } from "../shared/local-server.ts"; + +export interface AliyunOAuthLoginDeps { + identity: Identity; + settings: Settings; + authStore: Pick; + output: Pick; + localize?: (text: LocalizedText) => string; + writeStderr?: (text: string) => void; + openBrowser?: (url: string) => void | Promise; + onAuthUrl?: (url: string) => void | Promise; +} + +export interface AliyunOAuthLoginOptions { + clientId?: string; + scope?: string; + oauthBaseUrl?: string; + authorizationUrl?: string; + modelstudioHost?: string; + consoleGateway?: string; + bailiancontrolHost?: string; + consoleRegion?: string; + noBrowser?: boolean; + callbackTimeoutMs?: number; + signal?: AbortSignal; +} + +type LoginProfile = Omit; +const CALLBACK_TIMEOUT_MS = 15 * 60 * 1000; +const OAUTH_CALLBACK_PATH = "/oauth/callback"; +const DEFAULT_MODEL_STUDIO_HOST = resolveModelStudioHost("cn-beijing")!; +const DEFAULT_CONSOLE_GATEWAY = resolveConsoleGatewayOrigin("cn-beijing", "domestic"); + +function localize(deps: AliyunOAuthLoginDeps, text: LocalizedText): string { + return deps.localize ? deps.localize(text) : typeof text === "string" ? text : text["en-US"]; +} + +function nonempty(value: string, flag: string): string { + if (!value.trim()) throw new UsageError(`${flag} must not be empty. / ${flag} 不能为空。`); + return value.trim(); +} + +function trustedPreEndpoint( + explicit: string | undefined, + stored: string | undefined, + trusted: string | undefined, + flag: string, + normalize: (value: string) => string, +): void { + // Check stored metadata independently: an explicit override must not hide a mismatched profile. + if ([explicit, stored].some((value) => value !== undefined && normalize(value) !== trusted)) { + throw new UsageError( + `${flag} must match the trusted pre-release endpoint in both flags and saved OAuth metadata. / 参数及已保存的 OAuth 配置中,${flag} 必须与可信预发端点一致。`, + ); + } +} + +function loginPlan( + settings: Settings, + options: AliyunOAuthLoginOptions, + previous?: AliyunOAuthProfile, +) { + const pre = settings.preControlPlane; + const clientId = + options.clientId ?? previous?.client_id ?? (pre ? ALIYUN_CLI_CLIENT_ID : undefined); + const scope = nonempty(options.scope ?? previous?.scope ?? ALIYUN_CLI_SCOPE, "--scope"); + const region = nonempty( + options.consoleRegion ?? + (pre && settings.consoleRegion) ?? + previous?.console_region ?? + "cn-beijing", + "--console-region", + ); + if (region !== "cn-beijing" || (pre && previous && previous.console_region !== "cn-beijing")) { + throw new UsageError( + "Aliyun OAuth currently supports only cn-beijing. / 阿里云 OAuth 目前仅支持 cn-beijing。", + ); + } + const normalizedClientId = clientId === undefined ? undefined : nonempty(clientId, "--client-id"); + const domains = { console_region: region, console_enabled: true, openapi_enabled: true }; + if (pre) { + const target = { region, site: settings.consoleSite ?? "domestic" }; + const gateway = + settings.dryRun && !pre.consoleGateway && target.site === "domestic" + ? undefined + : requirePreConsoleGateway(pre, target); + const normalizeOrigin = (value: string) => normalizeOAuthUrl(value, true); + trustedPreEndpoint( + options.authorizationUrl, + previous?.authorization_url, + PRE_ALIYUN_AUTHORIZATION_URL, + "--authorization-url", + normalizeOAuthUrl, + ); + trustedPreEndpoint( + options.oauthBaseUrl, + previous?.oauth_base_url, + PRE_ALIYUN_OAUTH_BASE_URL, + "--oauth-base-url", + normalizeOrigin, + ); + trustedPreEndpoint( + options.modelstudioHost, + previous?.modelstudio_host, + PRE_MODEL_STUDIO_HOST, + "--modelstudio-host", + normalizeOpenApiHost, + ); + trustedPreEndpoint( + options.bailiancontrolHost, + previous?.bailiancontrol_host, + PRE_BAILIAN_CONTROL_HOST, + "--bailiancontrol-host", + normalizeOpenApiHost, + ); + trustedPreEndpoint( + options.consoleGateway, + previous?.console_gateway, + gateway, + "--console-gateway", + normalizeOrigin, + ); + return { + client_id: normalizedClientId, + scope, + oauth_base_url: PRE_ALIYUN_OAUTH_BASE_URL, + authorization_url: PRE_ALIYUN_AUTHORIZATION_URL, + modelstudio_host: PRE_MODEL_STUDIO_HOST, + console_gateway: gateway, + bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + ...domains, + }; + } + const authorizationUrl = options.authorizationUrl ?? previous?.authorization_url; + const modelstudioHost = + options.modelstudioHost ?? previous?.modelstudio_host ?? DEFAULT_MODEL_STUDIO_HOST; + const consoleGateway = + options.consoleGateway ?? previous?.console_gateway ?? DEFAULT_CONSOLE_GATEWAY; + const bailiancontrolHost = options.bailiancontrolHost ?? previous?.bailiancontrol_host; + return { + client_id: normalizedClientId, + scope, + oauth_base_url: normalizeOAuthUrl( + options.oauthBaseUrl ?? previous?.oauth_base_url ?? ALIYUN_OAUTH_BASE_URL, + true, + ), + authorization_url: + authorizationUrl === undefined ? undefined : normalizeOAuthUrl(authorizationUrl), + modelstudio_host: normalizeOpenApiHost(modelstudioHost), + console_gateway: normalizeOAuthUrl(consoleGateway, true), + ...(bailiancontrolHost === undefined + ? {} + : { bailiancontrol_host: normalizeOpenApiHost(bailiancontrolHost) }), + ...domains, + }; +} + +function interrupted(deps: AliyunOAuthLoginDeps): BailianError { + return new BailianError( + localize(deps, { + "en-US": "Aliyun OAuth login was cancelled.", + "zh-CN": "阿里云 OAuth 登录已取消。", + }), + ExitCode.INTERRUPTED, + ); +} + +function assertActive(signal: AbortSignal, deps: AliyunOAuthLoginDeps): void { + if (signal.aborted) throw interrupted(deps); +} + +/** Only this process's callback server and listeners are owned by this function. */ +async function receiveCode( + deps: AliyunOAuthLoginDeps, + profile: LoginProfile, + proof: ReturnType, + options: AliyunOAuthLoginOptions, + signal: AbortSignal, +): Promise<{ code: string; redirectUri: string }> { + assertActive(signal, deps); + let finished = false; + let timer: ReturnType | undefined; + let resolveCode!: (code: string) => void; + let rejectCode!: (error: unknown) => void; + const completion = new Promise((resolve, reject) => { + resolveCode = resolve; + rejectCode = reject; + }); + // Binding and announcing the URL are asynchronous; rejection must already be observed. + void completion.catch(() => {}); + const settle = (code?: string, error?: unknown) => { + if (finished) return; + finished = true; + clearTimeout(timer); + if (error !== undefined) rejectCode(error); + else resolveCode(code!); + }; + const server = http.createServer((request, response) => { + response.setHeader("Content-Type", "text/plain; charset=utf-8"); + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Referrer-Policy", "no-referrer"); + response.setHeader("X-Content-Type-Options", "nosniff"); + if (request.method !== "GET") { + response.writeHead(405, { Allow: "GET" }); + response.end( + localize(deps, { "en-US": "Only GET is allowed.\n", "zh-CN": "仅允许 GET 请求。\n" }), + ); + return; + } + let callback: URL; + try { + callback = new URL(request.url ?? "/", "http://127.0.0.1"); + } catch { + response.writeHead(400); + response.end(localize(deps, { "en-US": "Invalid callback.\n", "zh-CN": "无效的回调。\n" })); + return; + } + if (callback.pathname !== OAUTH_CALLBACK_PATH) { + response.writeHead(404); + response.end(localize(deps, { "en-US": "Not found.\n", "zh-CN": "路径不存在。\n" })); + return; + } + if (finished) { + response.writeHead(409); + response.end( + localize(deps, { "en-US": "Login is no longer waiting.\n", "zh-CN": "登录已结束等待。\n" }), + ); + return; + } + let code: string; + try { + code = parseAliyunCallback(callback, proof.state); + } catch (error) { + response.writeHead(400); + // Invalid state/code must not consume the pending login; a valid-state denial does. + const denied = + callback.searchParams.getAll("state").length === 1 && + callback.searchParams.get("state") === proof.state && + callback.searchParams.has("error"); + if (denied) { + response.once("finish", () => settle(undefined, error)); + response.once("close", () => settle(undefined, error)); + } + response.end( + localize(deps, { "en-US": "OAuth callback rejected.\n", "zh-CN": "OAuth 回调被拒绝。\n" }), + ); + return; + } + // Flush the browser response before cleanup; a disconnected browser must not lose the code. + response.once("finish", () => settle(code)); + response.once("close", () => settle(code)); + response.end( + localize(deps, { + "en-US": "Authorization received. You can close this page and return to the terminal.\n", + "zh-CN": "已收到授权,请关闭本页并返回终端查看登录结果。\n", + }), + ); + }); + const onError = (error: Error) => settle(undefined, error); + const onAbort = () => settle(undefined, interrupted(deps)); + server.on("error", onError); + signal.addEventListener("abort", onAbort, { once: true }); + const writeStderr = + deps.writeStderr ?? + ((text: string) => { + process.stderr.write(text); + }); + try { + const port = await listenLocalServer(server, 0); + assertActive(signal, deps); + const redirectUri = normalizeOAuthUrl(`http://127.0.0.1:${port}${OAUTH_CALLBACK_PATH}`); + const authUrl = normalizeOAuthUrl(aliyunAuthorizationUrl(profile, redirectUri, proof)); + timer = setTimeout( + () => + settle( + undefined, + new BailianError( + localize(deps, { + "en-US": "Aliyun OAuth login timed out waiting for the local callback.", + "zh-CN": "阿里云 OAuth 登录等待本机回调超时。", + }), + ExitCode.TIMEOUT, + ), + ), + options.callbackTimeoutMs ?? CALLBACK_TIMEOUT_MS, + ); + writeStderr( + `${localize(deps, { + "en-US": "Open this login URL in a browser on this machine:", + "zh-CN": "请在本机浏览器中打开以下登录地址:", + })}\n${authUrl}\n${localize(deps, { + "en-US": "Waiting for the local OAuth callback. Press Ctrl+C to cancel.", + "zh-CN": "正在等待本机 OAuth 回调。按 Ctrl+C 取消。", + })}\n`, + ); + if (deps.onAuthUrl) + void Promise.resolve() + .then(() => deps.onAuthUrl!(authUrl)) + .catch(onError); + if (!options.noBrowser) { + // Never await browser launch: it can fail, hang, or deliver an immediate callback. + void Promise.resolve() + .then(() => (deps.openBrowser ?? openInBrowser)(authUrl)) + .catch(() => { + if (!finished) + writeStderr( + `${localize(deps, { + "en-US": "Could not open the browser. Open the URL above manually.", + "zh-CN": "无法自动打开浏览器,请手动打开上方地址。", + })}\n`, + ); + }); + } + return { code: await completion, redirectUri }; + } finally { + finished = true; + clearTimeout(timer); + signal.removeEventListener("abort", onAbort); + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }); + server.off("error", onError); + } +} + +/** Preserve the primary failure and its API context, but never expose known login secrets. */ +function safeLoginError(error: unknown, secrets: string[]): unknown { + const scrub = (value: string | undefined) => { + if (value === undefined) return undefined; + for (const secret of secrets) if (secret) value = value.replaceAll(secret, "[REDACTED]"); + return value; + }; + if (!(error instanceof Error)) return new BailianError(scrub(String(error))!, ExitCode.GENERAL); + const original = error instanceof BailianError ? error : undefined; + const cause = + error.cause instanceof Error + ? { + message: scrub(error.cause.message), + code: scrub((error.cause as NodeJS.ErrnoException).code), + } + : typeof error.cause === "string" + ? scrub(error.cause) + : undefined; + if (!original) { + // Keep runtime's transport/timeout/errno classification without retaining secret-bearing stacks. + const sanitized = + error instanceof TypeError + ? new TypeError(scrub(error.message), { cause }) + : new Error(scrub(error.message), { cause }); + sanitized.name = scrub(error.name)!; + const code = (error as NodeJS.ErrnoException).code; + if (typeof code === "string") (sanitized as NodeJS.ErrnoException).code = scrub(code); + return sanitized; + } + return new BailianError( + scrub(error.message)!, + original?.exitCode ?? ExitCode.GENERAL, + scrub(original?.hint), + { + ...(original?.api + ? { + api: { + ...original.api, + apiCode: scrub(original.api.apiCode), + requestId: scrub(original.api.requestId), + }, + } + : {}), + rawResponse: scrub(original?.rawResponse), + cause, + }, + ); +} + +export async function runAliyunOAuthLogin( + deps: AliyunOAuthLoginDeps, + options: AliyunOAuthLoginOptions = {}, +): Promise { + // Static dry-run never describes existing credentials, generates proof, binds, or reads secrets. + const { dryRun, preControlPlane } = deps.settings; + const plan = loginPlan( + deps.settings, + options, + dryRun ? undefined : deps.authStore.describe().aliyunOAuth, + ); + const missing = [ + ...(!plan.authorization_url ? ["--authorization-url"] : []), + ...(!plan.client_id ? ["--client-id"] : []), + ...(!plan.console_gateway ? ["BAILIAN_PRE_CONSOLE_GATEWAY"] : []), + ]; + const config = deps.settings.configName ?? "default"; + if (dryRun) { + const missingClientId = missing.includes("--client-id"); + const preEndpoints = preControlPlane + ? `\n${localize(deps, { "en-US": "Pre-release endpoints", "zh-CN": "预发端点" })}: ${[ + plan.authorization_url, + plan.oauth_base_url, + plan.modelstudio_host, + plan.bailiancontrol_host, + plan.console_gateway, + ] + .filter(Boolean) + .join(", ")}` + : ""; + deps.output.result( + { + action: "auth.login", + method: "aliyun", + config, + no_browser: !!options.noBrowser, + ...(preControlPlane ? { environment: "pre" } : {}), + plan, + missing, + }, + { + text: localize(deps, { + "en-US": `Would authorize Aliyun OAuth with a random loopback port, exchange STS, validate Console access and save the session. ${missingClientId ? "Missing required options" : "Missing endpoints"}: ${missing.join(", ") || "none"}.${preEndpoints}`, + "zh-CN": `将通过随机回环端口完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。${missingClientId ? "缺少必填选项" : "缺少端点"}:${missing.join("、") || "无"}。${preEndpoints}`, + }), + }, + ); + return; + } + if (!plan.client_id) { + throw new UsageError( + localize(deps, { + "en-US": `Provide ${missing.join(" and ")} for the first login outside the pre-release control plane.`, + "zh-CN": `非预发控制面首次登录请提供 ${missing.join(" 和 ")}。`, + }), + ); + } + if (!plan.authorization_url) { + throw new UsageError( + localize(deps, { + "en-US": + "Provide --authorization-url for the first login; the authorization endpoint will not be guessed.", + "zh-CN": "首次登录请提供 --authorization-url;不会猜测授权地址。", + }), + ); + } + if ( + options.callbackTimeoutMs !== undefined && + (!Number.isFinite(options.callbackTimeoutMs) || options.callbackTimeoutMs <= 0) + ) { + throw new UsageError("callbackTimeoutMs must be positive. / callbackTimeoutMs 必须为正数。"); + } + const profile: LoginProfile = { + ...plan, + client_id: plan.client_id, + authorization_url: plan.authorization_url, + // The live preflight above requires a configured gateway; only dry-run may omit it. + console_gateway: plan.console_gateway!, + }; + const cancellation = new AbortController(); + const signal = options.signal + ? AbortSignal.any([options.signal, cancellation.signal]) + : cancellation.signal; + const onSignal = () => cancellation.abort(); + process.once("SIGINT", onSignal); + process.once("SIGTERM", onSignal); + const oauthDeps = { identity: deps.identity, timeout: deps.settings.timeout }; + const secrets: string[] = []; + let session: AliyunOAuthSession | undefined; + let saved = false; + try { + assertActive(signal, deps); + const proof = createOAuthProofKey(); + secrets.push(proof.verifier); + const { code, redirectUri } = await receiveCode(deps, profile, proof, options, signal); + secrets.push(code); + assertActive(signal, deps); + session = await exchangeAliyunCode(profile, code, proof.verifier, redirectUri, oauthDeps); + secrets.push(session.accessToken, session.refreshToken); + assertActive(signal, deps); + session.sts = await exchangeAliyunSts(profile, session.accessToken, oauthDeps); + secrets.push(session.sts.accessKeyId, session.sts.accessKeySecret, session.sts.securityToken); + assertActive(signal, deps); + const settings: Settings = { + ...deps.settings, + consoleRegion: "cn-beijing", + consoleSite: "domestic", + consoleSwitchAgent: undefined, + }; + const { cliAccessToken } = await generateCLIAccessToken({ + identity: deps.identity, + settings, + baseUrl: normalizeOAuthUrl(`https://${profile.modelstudio_host}`, true), + modelStudioHost: profile.modelstudio_host, + accessKeyId: session.sts.accessKeyId, + accessKeySecret: session.sts.accessKeySecret, + securityToken: session.sts.securityToken, + }); + secrets.push(cliAccessToken); + assertActive(signal, deps); + const target = { + region: "cn-beijing", + site: "domestic" as const, + gateway: profile.console_gateway, + }; + await validateConsoleAccessToken({ ...target, token: cliAccessToken }, settings); + assertActive(signal, deps); + // Console TTL is intentionally absent: GenerateCLIAccessToken has no confirmed TTL field. + session.consoleTokens = { [consoleCredentialKey(target)]: { token: cliAccessToken } }; + profile.access_token_expires_at = session.accessTokenExpiresAt; + profile.sts_expires_at = session.sts.expiresAt; + await deps.authStore.loginAliyun(profile, session); + saved = true; + deps.output.result( + { authenticated: true, method: "aliyun", config, console: true, openapi: true }, + { + text: localize(deps, { + "en-US": `Authenticated with Aliyun OAuth (config: ${config}; console: true; openapi: true).`, + "zh-CN": `阿里云 OAuth 登录成功(配置:${config};console:true;openapi:true)。`, + }), + }, + ); + } catch (error) { + if (!saved && session?.refreshToken) { + // Cleanup failure must not replace the exchange/validation/persistence error. + await revokeAliyunTokens(profile, session.refreshToken, { + ...oauthDeps, + timeout: Math.min(oauthDeps.timeout, 5), + }).catch(() => {}); + } + throw safeLoginError(error, secrets); + } finally { + process.off("SIGINT", onSignal); + process.off("SIGTERM", onSignal); + } +} + +export default defineCommand({ + description: { "en-US": "Authenticate with Aliyun OAuth", "zh-CN": "通过阿里云 OAuth 登录" }, + auth: "none", + usageArgs: + "--login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ]", + exampleArgs: [ + "--login aliyun --client-id --authorization-url ", + "--login aliyun --client-id --authorization-url --modelstudio-host --console-gateway ", + ], + flags: { + login: { + type: "string", + required: true, + choices: ["aliyun"] as const, + valueHint: "", + description: { "en-US": "Login method: aliyun", "zh-CN": "登录方式:aliyun" }, + }, + clientId: { + type: "string", + valueHint: "", + description: { + "en-US": "OAuth client ID; required for the first login outside pre-release", + "zh-CN": "OAuth 客户端 ID;非预发环境首次登录必须提供", + }, + }, + scope: { + type: "string", + valueHint: "", + description: { + "en-US": `OAuth scope (default: ${ALIYUN_CLI_SCOPE})`, + "zh-CN": `OAuth 授权范围(默认:${ALIYUN_CLI_SCOPE})`, + }, + }, + oauthBaseUrl: { + type: "string", + valueHint: "", + description: { + "en-US": `OAuth token service origin (production default: ${ALIYUN_OAUTH_BASE_URL})`, + "zh-CN": `OAuth 令牌服务源站(线上默认:${ALIYUN_OAUTH_BASE_URL})`, + }, + }, + authorizationUrl: { + type: "string", + valueHint: "", + description: { + "en-US": "Explicit authorization URL; required for the first login outside pre-release", + "zh-CN": "显式授权地址;非预发环境首次登录必须提供", + }, + }, + modelstudioHost: { + type: "string", + valueHint: "", + description: { + "en-US": `Model Studio POP hostname override (production default: ${DEFAULT_MODEL_STUDIO_HOST})`, + "zh-CN": `Model Studio POP 主机名覆盖(线上默认:${DEFAULT_MODEL_STUDIO_HOST})`, + }, + }, + consoleGateway: { + type: "string", + valueHint: "", + description: { + "en-US": `Console gateway origin override (production default: ${DEFAULT_CONSOLE_GATEWAY})`, + "zh-CN": `控制台网关源站覆盖(线上默认:${DEFAULT_CONSOLE_GATEWAY})`, + }, + }, + bailiancontrolHost: { + type: "string", + valueHint: "", + description: { + "en-US": "Optional Bailian Control OpenAPI hostname", + "zh-CN": "可选 Bailian Control OpenAPI 主机名", + }, + }, + consoleRegion: { + type: "string", + choices: ["cn-beijing"] as const, + valueHint: "", + description: { + "en-US": "Console region (only cn-beijing; default: cn-beijing)", + "zh-CN": "控制台地域(仅支持 cn-beijing;默认:cn-beijing)", + }, + }, + noBrowser: { + type: "switch", + description: { + "en-US": "Do not open the browser automatically; still wait for the local callback", + "zh-CN": "不自动打开浏览器;仍等待本机回调", + }, + }, + }, + notes: [ + { + "en-US": + "Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. No device flow or remote callback import is supported.", + "zh-CN": + "非预发环境首次登录需要显式指定客户端 ID 和已确认的授权地址。预发端点覆盖必须与可信端点一致,并且必须配置 CLI 网关。不支持设备授权或导入远程回调。", + }, + { + "en-US": + "Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match.", + "zh-CN": + "IAM 重定向 URI 登记为 http://127.0.0.1:12345/oauth/callback。NativeApp 回环端口可随机,协议、主机和路径必须一致。", + }, + ], + async run(ctx) { + await runAliyunOAuthLogin( + { + identity: ctx.identity, + settings: ctx.settings, + authStore: ctx.authStore, + output: ctx.output, + localize: ctx.localize, + }, + ctx.flags, + ); + }, +}); diff --git a/packages/commands/src/commands/auth/console-ui.ts b/packages/commands/src/commands/auth/console-ui.ts index a96c255cc..fb7789658 100644 --- a/packages/commands/src/commands/auth/console-ui.ts +++ b/packages/commands/src/commands/auth/console-ui.ts @@ -7,6 +7,7 @@ import { type Settings, } from "bailian-cli-core"; import { runConsoleLogin, resolveConsoleOrigin } from "./login-console.ts"; +import { logoutStoredAuth } from "./logout.ts"; /** Read-only auth snapshot the config UI account widget renders. bl stores no * user profile (name/avatar), so this exposes only which credential domains @@ -15,6 +16,7 @@ export interface AuthUiStatus { authenticated: boolean; methods: { apiKey: boolean; console: boolean; openapi: boolean }; primary: "console" | "apiKey" | "openapi" | null; + environment?: "pre"; region?: string; site?: "domestic" | "international"; masked?: string; @@ -30,7 +32,7 @@ export interface AuthUiBridge { status(): AuthUiStatus; /** Start browser-based console login (fire-and-forget; UI polls status). */ startConsoleLogin(): void; - /** Clear all stored credentials. Returns whether anything changed. */ + /** Log out of the bound profile; pre-release leaves model credentials intact. */ logout(): Promise; } @@ -43,49 +45,67 @@ export function makeAuthUiBridge(ctx: { localize?: (text: LocalizedText) => string; }): AuthUiBridge { const { identity, settings, authStore, localize, output } = ctx; + const pre = settings.preControlPlane !== undefined; + const warnLoginFailure = (error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + output.warning({ + message: { + "en-US": `Console login failed: ${message}`, + "zh-CN": `控制台登录失败:${message}`, + }, + code: "CONSOLE_LOGIN_FAILED", + }); + }; return { status() { const a = authStore.describe(); - const methods = { apiKey: !!a.apiKey, console: !!a.console, openapi: !!a.openapi }; + const methods = { + apiKey: !!a.apiKey, + console: !!(a.console || a.aliyunOAuth?.console_enabled), + openapi: !!(a.openapi || a.aliyunOAuth?.openapi_enabled), + }; let masked: string | undefined; if (a.console) masked = maskToken(a.console.token); else if (a.apiKey) masked = maskToken(a.apiKey.token); else if (a.openapi) masked = maskToken(a.openapi.accessKeyId); - const primary = a.console ? "console" : a.apiKey ? "apiKey" : a.openapi ? "openapi" : null; + const primary = methods.console + ? "console" + : methods.apiKey + ? "apiKey" + : methods.openapi + ? "openapi" + : null; return { authenticated: methods.apiKey || methods.console || methods.openapi, methods, primary, - region: a.console?.region, - site: a.console?.site, + ...(pre ? { environment: "pre" as const } : {}), + region: + a.console?.region ?? + (a.aliyunOAuth?.console_enabled ? a.aliyunOAuth.console_region : undefined), + site: a.console?.site ?? (a.aliyunOAuth?.console_enabled ? "domestic" : undefined), masked, }; }, startConsoleLogin() { - const origin = resolveConsoleOrigin(authStore.describe().console?.site); - // Mirror the CLI (`bl auth login --console`): request an api_key from the - // console only when one isn't already stored, so a first console login in - // the config UI also provisions the model api_key (not just access_token). - const hasApiKey = !!authStore.stored().apiKey; - // runConsoleLogin opens the browser and runs its own callback server - // (up to 15 min). We don't await it — the config UI polls the status - // endpoint to detect completion. Errors are logged, not surfaced. - void runConsoleLogin( - origin, - { identity, settings, authStore, localize, output }, - { - needApiKey: !hasApiKey, - }, - ).catch((err: unknown) => { - const msg = err instanceof Error ? err.message : String(err); - output.warning({ - message: { "en-US": `Console login failed: ${msg}`, "zh-CN": `控制台登录失败:${msg}` }, - code: "CONSOLE_LOGIN_FAILED", - }); - }); + const origin = pre ? undefined : resolveConsoleOrigin(authStore.describe().console?.site); + // Keep launch Profile and environment bound for the entire callback. The UI only polls for completion. + try { + void runConsoleLogin( + origin, + { identity, settings, authStore, localize, output }, + { + needApiKey: !pre && !authStore.stored().apiKey, + }, + ).catch(warnLoginFailure); + } catch (error) { + // Endpoint preflight failures are synchronous; never tell the UI login was started. + warnLoginFailure(error); + throw error; + } }, logout() { - return authStore.logout("all"); + return logoutStoredAuth(authStore, "all", pre); }, }; } diff --git a/packages/commands/src/commands/auth/generate-access-token.ts b/packages/commands/src/commands/auth/generate-access-token.ts index 9cf89bb6a..78b5df1d7 100644 --- a/packages/commands/src/commands/auth/generate-access-token.ts +++ b/packages/commands/src/commands/auth/generate-access-token.ts @@ -1,53 +1,41 @@ -import { defineCommand, generateCLIAccessToken, type FlagsDef } from "bailian-cli-core"; - -const FLAGS = { - accessKeyId: { - type: "string", - valueHint: "", - description: { "en-US": "Alibaba Cloud Access Key ID", "zh-CN": "阿里云 Access Key ID" }, - required: true, - }, - accessKeySecret: { - type: "string", - valueHint: "", - description: { - "en-US": "Alibaba Cloud Access Key Secret", - "zh-CN": "阿里云 Access Key Secret", - }, - required: true, - }, - securityToken: { - type: "string", - valueHint: "", - description: { - "en-US": "Alibaba Cloud STS Security Token to store (optional)", - "zh-CN": "要保存的阿里云 STS Security Token(可选)", - }, - }, -} satisfies FlagsDef; +import { defineCommand, generateCLIAccessToken } from "bailian-cli-core"; export default defineCommand({ description: { - "en-US": "Generate a CLI access token using OpenAPI AK/SK", - "zh-CN": "使用 OpenAPI AK/SK 生成 CLI Access Token", + "en-US": "Generate a CLI access token using OpenAPI credentials", + "zh-CN": "使用 OpenAPI 凭据生成 CLI Access Token", }, - auth: "none", - usageArgs: "--access-key-id --access-key-secret --security-token ", - flags: FLAGS, - exampleArgs: ["--access-key-id LTAIxxxxx --access-key-secret xxxxx --security-token "], + auth: "openapi", + usageArgs: "[flags]", + exampleArgs: ["", "--access-key-id LTAIxxxxx --access-key-secret xxxxx --security-token "], async run(ctx) { - const { identity, settings, flags } = ctx; - - const resp = await generateCLIAccessToken({ + const { identity, settings } = ctx; + if (settings.dryRun) { + const pre = settings.preControlPlane + ? { + environment: "pre", + host: ctx.client.resolveOpenApiHost("modelstudio.cn-beijing.aliyuncs.com"), + } + : {}; + ctx.output.result( + { action: "auth.generate-access-token", config: settings.configName ?? "default", ...pre }, + { + text: ctx.localize({ + "en-US": + "Would generate a CLI access token using the selected OpenAPI credentials without saving it.", + "zh-CN": "将使用所选 OpenAPI 凭据生成 CLI Access Token,不保存该令牌。", + }), + }, + ); + return; + } + const response = await generateCLIAccessToken({ identity, settings, debug: (record) => ctx.output.debug(record), baseUrl: ctx.client.baseUrl, - accessKeyId: flags.accessKeyId, - accessKeySecret: flags.accessKeySecret, - securityToken: flags.securityToken || undefined, + client: ctx.client, }); - - ctx.output.result(resp); + ctx.output.result(response); }, }); diff --git a/packages/commands/src/commands/auth/login-console.ts b/packages/commands/src/commands/auth/login-console.ts index 7a13219a2..9b40783f0 100644 --- a/packages/commands/src/commands/auth/login-console.ts +++ b/packages/commands/src/commands/auth/login-console.ts @@ -5,6 +5,9 @@ import { formatCommand, BailianError, ExitCode, + effectiveConsoleGatewayConfig, + requirePreConsoleGateway, + requirePreConsoleOrigin, validateConsoleAccessToken, type ConsoleGatewayTarget, type CommandOutput, @@ -48,6 +51,15 @@ export function resolveConsoleOrigin(site?: string): string { return (site && CONSOLE_ORIGINS[site]) || CONSOLE_ORIGINS.domestic!; } +type ConsoleLoginTarget = Omit; + +/** Pre-release Console defaults are independent of the model Base URL. */ +export function resolveConsoleLoginTarget(settings: Settings): ConsoleLoginTarget { + const { consoleRegion, consoleSite, consoleSwitchAgent } = + effectiveConsoleGatewayConfig(settings); + return { region: consoleRegion, site: consoleSite, switchAgent: consoleSwitchAgent }; +} + function readBodyBounded(req: http.IncomingMessage): Promise { return new Promise((resolve, reject) => { let size = 0; @@ -380,8 +392,12 @@ function listenServerOnFreeLocalPort(server: http.Server): Promise { /** 人工导入只接受管道中的原始 token,不把凭证放进 argv 或终端回显。 */ export async function runConsoleTokenLogin( deps: LoginDeps, - target: Omit, + target: ConsoleLoginTarget, ): Promise { + const pre = deps.settings.preControlPlane; + const validationTarget = pre + ? { ...target, gateway: requirePreConsoleGateway(pre, target) } + : target; const input = process.stdin; if (input.isTTY) { throw new BailianError( @@ -421,7 +437,7 @@ export async function runConsoleTokenLogin( ExitCode.USAGE, ); } - await validateConsoleAccessToken({ ...target, token }, deps.settings, { + await validateConsoleAccessToken({ ...validationTarget, token }, deps.settings, { debug: deps.output.debug, }); await deps.authStore.login({ @@ -431,11 +447,34 @@ export async function runConsoleTokenLogin( }); } -export async function runConsoleLogin( +type ConsoleBrowserOptions = { needApiKey?: boolean; noBrowser?: boolean }; + +export function runConsoleLogin( + consoleOrigin: string | undefined, + deps: LoginDeps, + opts?: ConsoleBrowserOptions, +): Promise { + const pre = deps.settings.preControlPlane; + if (!pre) { + return waitForConsoleLogin( + consoleOrigin ?? resolveConsoleOrigin(deps.settings.consoleSite), + deps, + opts, + ); + } + const target = resolveConsoleLoginTarget(deps.settings); + const origin = requirePreConsoleOrigin(pre, target); + const gateway = requirePreConsoleGateway(pre, target); + return waitForConsoleLogin(origin, deps, opts, { ...target, gateway }); +} + +async function waitForConsoleLogin( consoleOrigin: string, deps: LoginDeps, - opts?: { needApiKey?: boolean; noBrowser?: boolean }, + opts?: ConsoleBrowserOptions, + preTarget?: ConsoleLoginTarget, ): Promise { + const needApiKey = !preTarget && opts?.needApiKey; const state = randomBytes(16).toString("hex"); let callbackError: unknown; let savedSessionWithoutApiKey = false; @@ -509,27 +548,56 @@ export async function runConsoleLogin( return; } + if ( + preTarget && + ((consoleSite && consoleSite !== preTarget.site) || + (consoleRegion && consoleRegion !== preTarget.region)) + ) { + res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" }); + res.end( + localizeLogin(deps, { + "en-US": "Callback does not match the pre-release Console login target.\n", + "zh-CN": "回调与预发控制台登录目标不匹配。\n", + }), + ); + return; + } + savingCredentials = true; clearTimeout(timer); try { - const callbackPatch: AuthPersistPatch = { - access_token: accessToken || undefined, - console_site: (consoleSite || undefined) as ConfigFile["console_site"], - console_region: consoleRegion || undefined, - console_switch_agent: consoleSwitchAgent ? Number(consoleSwitchAgent) : undefined, - workspace_id: workspaceId || undefined, - }; - if (apiKey) { - await persistApiKey(deps, apiKey, { - persistBaseUrl: baseUrl || undefined, - persistPatch: callbackPatch, + if (preTarget) { + await validateConsoleAccessToken({ ...preTarget, token: accessToken }, deps.settings, { + debug: deps.output.debug, }); - } else { + // The browser cannot move the credential off the original Console target or set model config. await deps.authStore.login({ - ...callbackPatch, - base_url: baseUrl || undefined, + access_token: accessToken, + console_site: preTarget.site, + console_region: preTarget.region, + console_switch_agent: preTarget.switchAgent, + workspace_id: workspaceId || undefined, }); - savedSessionWithoutApiKey = true; + } else { + const callbackPatch: AuthPersistPatch = { + access_token: accessToken, + console_site: (consoleSite || undefined) as ConfigFile["console_site"], + console_region: consoleRegion || undefined, + console_switch_agent: consoleSwitchAgent ? Number(consoleSwitchAgent) : undefined, + workspace_id: workspaceId || undefined, + }; + if (apiKey) { + await persistApiKey(deps, apiKey, { + persistBaseUrl: baseUrl || undefined, + persistPatch: callbackPatch, + }); + } else { + await deps.authStore.login({ + ...callbackPatch, + base_url: baseUrl || undefined, + }); + savedSessionWithoutApiKey = true; + } } savedCredentials = true; } catch (error: unknown) { @@ -573,7 +641,7 @@ export async function runConsoleLogin( } let loginUrl = `${consoleOrigin}/console-login?notice=127.0.0.1:${port}?state=${encodeURIComponent(state)}`; - if (opts?.needApiKey) { + if (needApiKey) { loginUrl += "&needapikey=true"; } @@ -642,7 +710,7 @@ export async function runConsoleLogin( ); } - if (opts?.needApiKey && savedSessionWithoutApiKey) { + if (needApiKey && savedSessionWithoutApiKey) { deps.output.warning({ message: { "en-US": `Saved the console session only. Model commands still need an API key: ${formatCommand(deps.identity, "auth login --console")}, or ${formatCommand(deps.identity, "auth login --api-key ")}`, diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index 89d328004..1c19e11d0 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -8,9 +8,17 @@ import { validateConsoleAccessToken, getModelProfilePreset, normalizeModelBaseUrl, + PRE_MODEL_STUDIO_HOST, + requirePreConsoleGateway, + requirePreConsoleOrigin, + type Settings, } from "bailian-cli-core"; import { persistApiKey, validateApiKey } from "./login-api-key.ts"; -import { resolveConsoleOrigin, runConsoleLogin, runConsoleTokenLogin } from "./login-console.ts"; +import { + resolveConsoleLoginTarget, + runConsoleLogin, + runConsoleTokenLogin, +} from "./login-console.ts"; const LOGIN_MODE_HINT = "Choose exactly one login mode: --api-key, --console, or --open-api"; @@ -18,6 +26,35 @@ function hasValue(value: unknown): value is string { return typeof value === "string" && value.trim().length > 0; } +function previewPreLogin( + settings: Settings, + mode: "browser" | "token" | "openapi", + target = resolveConsoleLoginTarget(settings), +) { + const pre = settings.preControlPlane; + if (!pre) return undefined; + const gateway = pre.consoleGateway ? requirePreConsoleGateway(pre, target) : undefined; + const missing = gateway ? [] : ["BAILIAN_PRE_CONSOLE_GATEWAY"]; + let origin: string | undefined; + if (mode === "browser") { + if (pre.consoleOrigin) origin = requirePreConsoleOrigin(pre, target); + else missing.push("BAILIAN_PRE_CONSOLE_ORIGIN"); + } + const endpoints = { + ...(origin ? { console_origin: origin } : {}), + ...(gateway ? { console_gateway: gateway } : {}), + ...(mode === "openapi" ? { modelstudio_host: PRE_MODEL_STUDIO_HOST } : {}), + }; + const addresses = Object.values(endpoints).join(", "); + return { + result: { environment: "pre", endpoints, missing }, + text: { + "en-US": `Control plane: pre-release. Endpoints: ${addresses || "none configured"}. Missing: ${missing.join(", ") || "none"}.`, + "zh-CN": `控制面:预发。端点:${addresses || "尚未配置"}。缺少:${missing.join("、") || "无"}。`, + }, + }; +} + export default defineCommand({ description: { "en-US": @@ -48,9 +85,9 @@ export default defineCommand({ type: "switch", description: { "en-US": - "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", + "Sign in via browser (China by default; use --console-site international for the international site). Outside pre-release, creates an ordinary API key if needed; subscription plans require --api-key", "zh-CN": - "通过浏览器登录(默认中国站;国际站使用 --console-site international)。需要时会创建普通 API Key;订阅计划必须使用 --api-key 登录", + "通过浏览器登录(默认中国站;国际站使用 --console-site international)。非预发环境下按需创建普通 API Key;订阅计划必须使用 --api-key 登录", }, }, noBrowser: { @@ -158,6 +195,7 @@ export default defineCommand({ }, async run(ctx) { const { identity, settings, flags } = ctx; + const pre = settings.preControlPlane; const store = ctx.authStore; const deps = { identity, @@ -181,7 +219,17 @@ export default defineCommand({ const baseUrl = flags.baseUrl ? normalizeModelBaseUrl(flags.baseUrl) : undefined; if (flags.console) { + // Explicit Console site wins over the selected Profile; all requests use this target. + const consoleSettings: Settings = { + ...settings, + consoleSite: (flags.consoleSite || settings.consoleSite || "domestic") as + | "domestic" + | "international", + consoleRegion: flags.consoleRegion ?? settings.consoleRegion, + }; + const target = resolveConsoleLoginTarget(consoleSettings); if (settings.dryRun) { + const preview = previewPreLogin(settings, flags.tokenStdin ? "token" : "browser", target); ctx.output.result( { action: "auth.login", @@ -189,28 +237,30 @@ export default defineCommand({ token_stdin: !!flags.tokenStdin, no_browser: !!flags.noBrowser, config_file: store.path, + ...preview?.result, }, { - text: ctx.localize( - flags.tokenStdin - ? { - "en-US": - "Would read a console token from stdin, validate it and save it without opening a browser or local server.", - "zh-CN": "将从 stdin 读取控制台 token,校验后保存,不启动浏览器或本地服务。", - } - : flags.noBrowser + text: + ctx.localize( + flags.tokenStdin ? { "en-US": - "Would bind a free port on 127.0.0.1 and print the console login URL without opening a browser.", - "zh-CN": - "将在 127.0.0.1 监听空闲端口并打印控制台登录地址,不自动打开浏览器。", + "Would read a console token from stdin, validate it and save it without opening a browser or local server.", + "zh-CN": "将从 stdin 读取控制台 token,校验后保存,不启动浏览器或本地服务。", } - : { - "en-US": - "Would bind a free port on 127.0.0.1 and open the console login URL in your browser.", - "zh-CN": "将在 127.0.0.1 监听空闲端口并在浏览器中打开控制台登录地址。", - }, - ), + : flags.noBrowser + ? { + "en-US": + "Would bind a free port on 127.0.0.1 and print the console login URL without opening a browser.", + "zh-CN": + "将在 127.0.0.1 监听空闲端口并打印控制台登录地址,不自动打开浏览器。", + } + : { + "en-US": + "Would bind a free port on 127.0.0.1 and open the console login URL in your browser.", + "zh-CN": "将在 127.0.0.1 监听空闲端口并在浏览器中打开控制台登录地址。", + }, + ) + (preview ? `\n${ctx.localize(preview.text)}` : ""), }, ); return; @@ -225,15 +275,8 @@ export default defineCommand({ }), ExitCode.USAGE, ); - const hasApiKey = !!(key || store.stored().apiKey); - // 本次登录站点:参数缺省时用配置默认(file 里上次登录存的站点)。 - const site = flags.consoleSite || settings.consoleSite || "domestic"; if (flags.tokenStdin) { - await runConsoleTokenLogin(deps, { - site: site as "domestic" | "international", - region: flags.consoleRegion!, - switchAgent: settings.consoleSwitchAgent, - }); + await runConsoleTokenLogin({ ...deps, settings: consoleSettings }, target); finish( "console", ctx.localize({ @@ -243,10 +286,14 @@ export default defineCommand({ ); return; } - await runConsoleLogin(resolveConsoleOrigin(site), deps, { - needApiKey: !hasApiKey, - noBrowser: flags.noBrowser, - }); + await runConsoleLogin( + undefined, + { ...deps, settings: consoleSettings }, + { + needApiKey: !pre && !(key || store.stored().apiKey), + noBrowser: flags.noBrowser, + }, + ); finish( "console", ctx.localize({ @@ -259,35 +306,45 @@ export default defineCommand({ if (flags.openApi) { if (settings.dryRun) { + const preview = previewPreLogin(settings, "openapi"); ctx.output.result( - { action: "auth.login", method: "openapi", config_file: store.path }, + { action: "auth.login", method: "openapi", config_file: store.path, ...preview?.result }, { - text: ctx.localize({ - "en-US": "Would save OpenAPI AK/SK credentials and generate CLI access token.", - "zh-CN": "将保存 OpenAPI AK/SK 凭证并生成 CLI access token。", - }), + text: + ctx.localize({ + "en-US": "Would save OpenAPI AK/SK credentials and generate CLI access token.", + "zh-CN": "将保存 OpenAPI AK/SK 凭证并生成 CLI access token。", + }) + (preview ? `\n${ctx.localize(preview.text)}` : ""), }, ); return; } const resolvedBaseUrl = store.resolveBaseUrl(); - const target = resolveCLIAccessTokenTarget(settings, resolvedBaseUrl); + const target = pre + ? resolveConsoleLoginTarget(settings) + : resolveCLIAccessTokenTarget(settings, resolvedBaseUrl); + const gateway = pre ? requirePreConsoleGateway(pre, target) : undefined; + const tokenSettings = pre + ? { ...settings, consoleRegion: target.region, consoleSite: target.site } + : settings; ctx.output.progress({ "en-US": "Generating CLI access token...", "zh-CN": "正在生成 CLI access token...", }); const resp = await generateCLIAccessToken({ identity, - settings, + settings: tokenSettings, debug: (record) => ctx.output.debug(record), baseUrl: resolvedBaseUrl, accessKeyId: flags.accessKeyId!, accessKeySecret: flags.accessKeySecret!, }); const accessToken = resp.cliAccessToken; - await validateConsoleAccessToken({ ...target, token: accessToken }, settings, { - debug: (record) => ctx.output.debug(record), - }); + await validateConsoleAccessToken( + { ...target, ...(gateway ? { gateway } : {}), token: accessToken }, + tokenSettings, + { debug: (record) => ctx.output.debug(record) }, + ); await store.login({ access_key_id: flags.accessKeyId, access_key_secret: flags.accessKeySecret, diff --git a/packages/commands/src/commands/auth/logout.ts b/packages/commands/src/commands/auth/logout.ts index 219d691c3..154586589 100644 --- a/packages/commands/src/commands/auth/logout.ts +++ b/packages/commands/src/commands/auth/logout.ts @@ -1,4 +1,16 @@ -import { defineCommand } from "bailian-cli-core"; +import { defineCommand, type AuthStore } from "bailian-cli-core"; + +type LogoutScope = Parameters[0]; + +export async function logoutStoredAuth(store: AuthStore, scope: LogoutScope, pre: boolean) { + if (!pre || scope !== "all") return store.logout(scope); + + // Use only the bound control-plane store and leave all model settings intact. + const clearedOAuth = await store.logout("aliyun"); + const clearedConsole = await store.logout("console"); + const clearedOpenApi = await store.logout("openapi"); + return clearedOAuth || clearedConsole || clearedOpenApi; +} export default defineCommand({ description: { @@ -6,8 +18,23 @@ export default defineCommand({ "zh-CN": "清除已保存的凭证;完整退出还会清除模型 Base URL", }, auth: "none", - usageArgs: "[--console | --open-api] [--dry-run]", + usageArgs: "[--console | --open-api | --aliyun] [--dry-run]", + notes: [ + { + "en-US": + "Full logout or --aliyun revokes the OAuth refresh token. Partial Console/OpenAPI logout disables only that domain. Pre-release logout leaves model and production credentials intact.", + "zh-CN": + "完整退出或 --aliyun 会撤销 OAuth 刷新令牌;仅退出 Console/OpenAPI 时只停用对应鉴权域。预发退出不会清除模型或线上凭证。", + }, + ], flags: { + aliyun: { + type: "switch", + description: { + "en-US": "Revoke and remove only the Aliyun OAuth session", + "zh-CN": "仅撤销并移除阿里云 OAuth 会话", + }, + }, console: { type: "switch", description: { @@ -23,27 +50,59 @@ export default defineCommand({ }, }, }, - exampleArgs: ["", "--console", "--open-api", "--dry-run"], - validate: (f) => - f.console && f.openApi ? "Use only one scope: --console or --open-api" : undefined, + exampleArgs: ["", "--console", "--open-api", "--aliyun", "--dry-run"], + validate: (flags) => + [flags.console, flags.openApi, flags.aliyun].filter(Boolean).length > 1 + ? { + "en-US": "Use only one scope: --console, --open-api or --aliyun", + "zh-CN": "只能选择一个范围:--console、--open-api 或 --aliyun", + } + : undefined, async run(ctx) { const { settings, flags } = ctx; + const pre = settings.preControlPlane !== undefined; + const controlPlane = pre ? { environment: "pre" } : {}; + const environmentLine = pre + ? [ctx.localize({ "en-US": "Control plane: pre-release", "zh-CN": "控制面:预发" })] + : []; const store = ctx.authStore; const stored = store.stored(); - const scope = flags.console ? "console" : flags.openApi ? "openapi" : "all"; + const scope = flags.console + ? "console" + : flags.openApi + ? "openapi" + : flags.aliyun + ? "aliyun" + : "all"; const hasStoredAuth = scope === "console" ? stored.console : scope === "openapi" ? stored.openapi - : !!(stored.apiKey || stored.console || stored.openapi || stored.baseUrl); + : scope === "aliyun" + ? !!stored.aliyunOAuth + : !!( + stored.console || + stored.openapi || + stored.aliyunOAuth || + (!pre && (stored.apiKey || stored.baseUrl)) + ); + const credentialFields = + "access_token / access_key_id / access_key_secret / security_token / aliyun_oauth"; const fields = scope === "console" ? "access_token" : scope === "openapi" ? "access_key_id / access_key_secret / security_token" - : "api_key / base_url / access_token / access_key_id / access_key_secret / security_token"; + : scope === "aliyun" + ? ctx.localize({ + "en-US": "aliyun_oauth / local OAuth session", + "zh-CN": "aliyun_oauth / 本地 OAuth 会话", + }) + : pre + ? credentialFields + : `api_key / base_url / ${credentialFields}`; const empty = scope === "console" ? { @@ -55,10 +114,20 @@ export default defineCommand({ "en-US": "No OpenAPI AK/SK credentials to clear.", "zh-CN": "没有可清除的 OpenAPI AK/SK 凭证。", } - : { - "en-US": "No credentials or model Base URL to clear.", - "zh-CN": "没有可清除的凭证或模型 Base URL。", - }; + : scope === "aliyun" + ? { + "en-US": "No Aliyun OAuth session to clear.", + "zh-CN": "没有可清除的阿里云 OAuth 会话。", + } + : pre + ? { + "en-US": "No pre-release control-plane credentials to clear.", + "zh-CN": "没有可清除的预发控制面凭证。", + } + : { + "en-US": "No credentials or model Base URL to clear.", + "zh-CN": "没有可清除的凭证或模型 Base URL。", + }; if (settings.dryRun) { ctx.output.result( { @@ -67,9 +136,11 @@ export default defineCommand({ would_clear: hasStoredAuth, config: settings.configName ?? "default", config_file: store.path, + ...controlPlane, }, { text: [ + ...environmentLine, ctx.localize( hasStoredAuth ? { @@ -84,8 +155,9 @@ export default defineCommand({ ); return; } - const cleared = await store.logout(scope); + const cleared = await logoutStoredAuth(store, scope, pre); const lines = [ + ...environmentLine, ctx.localize( cleared ? { @@ -116,6 +188,7 @@ export default defineCommand({ cleared, config: settings.configName ?? "default", config_file: store.path, + ...controlPlane, }, { text: lines.join("\n") }, ); diff --git a/packages/commands/src/commands/auth/status.ts b/packages/commands/src/commands/auth/status.ts index e03d2f02b..76a923956 100644 --- a/packages/commands/src/commands/auth/status.ts +++ b/packages/commands/src/commands/auth/status.ts @@ -1,5 +1,10 @@ -import { formatCommand } from "bailian-cli-core"; -import { defineCommand, detectOutputFormat, maskToken } from "bailian-cli-core"; +import { + defineCommand, + detectOutputFormat, + formatCommand, + formatText, + maskToken, +} from "bailian-cli-core"; import { API_KEY_PAGE } from "bailian-cli-runtime"; export default defineCommand({ @@ -13,6 +18,16 @@ export default defineCommand({ const { identity, settings, localize } = ctx; const format = detectOutputFormat(settings.output); const auth = ctx.authStore.describe(); + const aliyunOAuth = auth.aliyunOAuth + ? { + client_id: auth.aliyunOAuth.client_id, + scope: auth.aliyunOAuth.scope, + console_enabled: auth.aliyunOAuth.console_enabled, + openapi_enabled: auth.aliyunOAuth.openapi_enabled, + access_token_expires_at: auth.aliyunOAuth.access_token_expires_at, + sts_expires_at: auth.aliyunOAuth.sts_expires_at, + } + : undefined; const apiKey = auth.apiKey ? { @@ -28,38 +43,70 @@ export default defineCommand({ region: auth.console.region, site: auth.console.site, } - : undefined; + : auth.aliyunOAuth?.console_enabled + ? { + source: "config", + method: "aliyun", + region: auth.aliyunOAuth.console_region, + site: "domestic", + } + : undefined; const openapi = auth.openapi ? { source: auth.openapi.source, access_key_id: maskToken(auth.openapi.accessKeyId), access_key_secret: maskToken(auth.openapi.accessKeySecret), } - : undefined; + : auth.aliyunOAuth?.openapi_enabled + ? { source: "config", method: "aliyun" } + : undefined; const authenticated = !!(apiKey || consoleCred || openapi); const configName = settings.configName ?? "default"; const configFile = ctx.authStore.path; + const pre = settings.preControlPlane !== undefined; + const controlPlane = pre ? { environment: "pre" } : {}; + const environmentLine = pre + ? localize({ "en-US": "Control plane: pre-release", "zh-CN": "控制面:预发" }) + : undefined; + const apiKeyLogin = formatCommand(identity, "auth login --api-key "); + const consoleLogin = formatCommand(identity, "auth login --console"); 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 ")}`, - }); + : localize( + pre + ? { + "en-US": `Model commands use separate credentials. To configure a model API key, run ${apiKeyLogin}`, + "zh-CN": `模型命令使用独立凭证。要配置模型 API Key,请运行 ${apiKeyLogin}`, + } + : { + "en-US": `No model API key is configured. Model commands need: ${consoleLogin}, or ${apiKeyLogin}`, + "zh-CN": `尚未配置模型 API Key。模型命令需要:${consoleLogin},或 ${apiKeyLogin}`, + }, + ); if (!authenticated) { - ctx.output.result({ + const result = { authenticated: false, + ...(aliyunOAuth ? { aliyun_oauth: aliyunOAuth } : {}), config: configName, config_file: configFile, message: "Not authenticated.", hint: [ - `API key (model): ${formatCommand(identity, "auth login --api-key ")} or DASHSCOPE_API_KEY`, - `Console gateway: ${formatCommand(identity, "auth login --console")}`, + `API key (model): ${apiKeyLogin} or DASHSCOPE_API_KEY`, + `Console gateway: ${consoleLogin}`, `OpenAPI (AK/SK): ${formatCommand(identity, "auth login --open-api --access-key-id --access-key-secret ")}`, `Get API Key: ${API_KEY_PAGE}`, ].join("\n"), - }); + }; + if (environmentLine) { + ctx.output.result( + { ...result, ...controlPlane }, + { text: `${environmentLine}\n${formatText(result)}` }, + ); + } else { + ctx.output.result(result); + } return; } @@ -68,17 +115,28 @@ export default defineCommand({ authenticated: true, config: configName, config_file: configFile, + ...controlPlane, api_key: apiKey, console: consoleCred, openapi, + ...(aliyunOAuth ? { aliyun_oauth: aliyunOAuth } : {}), ...(modelKeyHint ? { hint: modelKeyHint } : {}), }); return; } - const lines = [`Config: ${configName}`]; + const lines = environmentLine + ? [environmentLine, `Config: ${configName}`] + : [`Config: ${configName}`]; lines.push(`Config file: ${configFile}`); lines.push("Authentication Status:"); + if (aliyunOAuth) + lines.push( + localize({ + "en-US": ` Aliyun OAuth: configured; scope=${aliyunOAuth.scope}`, + "zh-CN": ` 阿里云 OAuth:已配置;scope=${aliyunOAuth.scope}`, + }), + ); if (apiKey) { lines.push(` API key (model): ${apiKey.source} ${apiKey.masked}`); } else { @@ -87,7 +145,7 @@ export default defineCommand({ } if (consoleCred) { lines.push( - ` Console gateway: ${consoleCred.source} ${consoleCred.masked} (${consoleCred.region}, ${consoleCred.site})`, + ` Console gateway: ${consoleCred.source} ${consoleCred.masked ?? localize({ "en-US": "OAuth managed", "zh-CN": "OAuth 托管" })} (${consoleCred.region}, ${consoleCred.site})`, ); } else { lines.push( @@ -95,7 +153,9 @@ export default defineCommand({ ); } if (openapi) { - lines.push(` OpenAPI (AK/SK): ${openapi.source} ${openapi.access_key_id}`); + lines.push( + ` OpenAPI (AK/SK): ${openapi.source} ${openapi.access_key_id ?? localize({ "en-US": "OAuth managed", "zh-CN": "OAuth 托管" })}`, + ); } else { lines.push( ` OpenAPI (AK/SK): not configured (run ${formatCommand(identity, "auth login --open-api")})`, @@ -106,9 +166,11 @@ export default defineCommand({ authenticated: true, config: configName, config_file: configFile, + ...controlPlane, api_key: apiKey, console: consoleCred, openapi, + ...(aliyunOAuth ? { aliyun_oauth: aliyunOAuth } : {}), ...(modelKeyHint ? { hint: modelKeyHint } : {}), }, { text: lines.join("\n") }, diff --git a/packages/commands/src/commands/config/ui-html.ts b/packages/commands/src/commands/config/ui-html.ts index 7b887752f..a0dd930e3 100644 --- a/packages/commands/src/commands/config/ui-html.ts +++ b/packages/commands/src/commands/config/ui-html.ts @@ -544,7 +544,7 @@ const PAGE_HTML = `

Config

-

Credentials and default models. The active profile (marked with a star) is used by every bl command. Click a profile to edit its settings.

+

Credentials and default models. Commands that read this configuration file use the active profile (marked with a star). Click a profile to edit its settings.

diff --git a/packages/commands/src/commands/config/ui-i18n.ts b/packages/commands/src/commands/config/ui-i18n.ts index 04a32fb18..12763555d 100644 --- a/packages/commands/src/commands/config/ui-i18n.ts +++ b/packages/commands/src/commands/config/ui-i18n.ts @@ -30,8 +30,8 @@ const ZH_CN_REPLACEMENTS: ReadonlyArray = [ ], [" was started.", " 的目录中执行。"], [ - "Credentials and default models. The active profile (marked with a star) is used by every bl command. Click a profile to edit its settings.", - "管理凭证和默认模型。所有 bl 命令都会使用带星标的已激活 Profile。点击 Profile 可编辑其设置。", + "Credentials and default models. Commands that read this configuration file use the active profile (marked with a star). Click a profile to edit its settings.", + "管理凭证和默认模型。读取此配置文件的命令会使用带星标的已激活 Profile。点击 Profile 可编辑其设置。", ], [ 'Agent skills discovered across every local agent module (~/.agents/skills plus each agent\'s skills folder). Installed via npx skills add.', diff --git a/packages/commands/src/commands/config/ui.ts b/packages/commands/src/commands/config/ui.ts index de4bf5424..a87b82919 100644 --- a/packages/commands/src/commands/config/ui.ts +++ b/packages/commands/src/commands/config/ui.ts @@ -10,7 +10,7 @@ import { ExitCode, normalizeConfigName, readConfigFile, - writeConfigFile, + mutateConfigFile, deleteConfigProfile, DEFAULT_LANGUAGE, REGIONS, @@ -183,7 +183,7 @@ export function createConfigUiServer( const uiLanguage = (): Language => { if (activatedUiProfile === null) return configUiLanguage(configStore); const configName = activatedUiProfile === "default" ? undefined : activatedUiProfile; - return readConfigFile(configName).language ?? DEFAULT_LANGUAGE; + return readConfigFile(configName, configStore.path).language ?? DEFAULT_LANGUAGE; }; return http.createServer(async (req, res) => { @@ -428,8 +428,12 @@ export function createConfigUiServer( sendJson(res, 400, { error: "login unavailable" }); return; } - authBridge.startConsoleLogin(); - sendJson(res, 200, { started: true }); + try { + authBridge.startConsoleLogin(); + sendJson(res, 200, { started: true }); + } catch (err) { + sendJson(res, 400, { error: errMessage(err) }); + } return; } @@ -646,16 +650,25 @@ export function createConfigUiServer( sendJson(res, 400, { error: errMessage(err) }); return; } - const existing = readConfigFile(normalized) as Record; - const saved = mergeUnmanagedProfileFields(existing, cleaned); - await writeConfigFile(saved, normalized); + let saved: Record = {}; + await mutateConfigFile( + (current) => { + saved = mergeUnmanagedProfileFields(current as Record, cleaned); + return saved; + }, + normalized, + { path: configStore.path }, + ); sendJson(res, 200, { saved, uiLanguage: uiLanguage() }); return; } if (path === "/api/profile" && method === "DELETE") { try { - const deleted = await deleteConfigProfile(u.searchParams.get("name") ?? undefined); + const deleted = await deleteConfigProfile( + u.searchParams.get("name") ?? undefined, + configStore.path, + ); sendJson(res, 200, { deleted, activeProfile: configStore.profiles().active }); } catch (err) { sendJson(res, 400, { error: errMessage(err) }); diff --git a/packages/commands/src/commands/finetune/fee.ts b/packages/commands/src/commands/finetune/fee.ts index 6c649fbf0..336cc5719 100644 --- a/packages/commands/src/commands/finetune/fee.ts +++ b/packages/commands/src/commands/finetune/fee.ts @@ -57,7 +57,7 @@ async function fetchTrainingPrice( }, }, }, - diagnostics, + { ...diagnostics, preControlPlane: settings.preControlPlane }, ); const responseData = unwrapResponse(result as Record); const list = (responseData.list as Record[]) ?? []; diff --git a/packages/commands/src/commands/token-plan/add-member.ts b/packages/commands/src/commands/token-plan/add-member.ts index 8962fb922..fff7ce0cd 100644 --- a/packages/commands/src/commands/token-plan/add-member.ts +++ b/packages/commands/src/commands/token-plan/add-member.ts @@ -67,7 +67,7 @@ export default defineCommand({ if (settings.dryRun) { const { endpoint, queryParams: query } = prepareTokenPlanRequest( - ctx.client.baseUrl, + ctx.client, API_PATH, queryParams, ); @@ -77,7 +77,6 @@ export default defineCommand({ const data = await callTokenPlanApi({ client: ctx.client, - baseUrl: ctx.client.baseUrl, action: API_ACTION, path: API_PATH, method: "POST", diff --git a/packages/commands/src/commands/token-plan/assign-seats.ts b/packages/commands/src/commands/token-plan/assign-seats.ts index edeec01f4..b32a55d26 100644 --- a/packages/commands/src/commands/token-plan/assign-seats.ts +++ b/packages/commands/src/commands/token-plan/assign-seats.ts @@ -64,7 +64,7 @@ export default defineCommand({ if (settings.dryRun) { const { endpoint, queryParams: query } = prepareTokenPlanRequest( - ctx.client.baseUrl, + ctx.client, API_PATH, queryParams, ); @@ -74,7 +74,6 @@ export default defineCommand({ const data = await callTokenPlanApi({ client: ctx.client, - baseUrl: ctx.client.baseUrl, action: API_ACTION, path: API_PATH, method: "POST", diff --git a/packages/commands/src/commands/token-plan/create-key.ts b/packages/commands/src/commands/token-plan/create-key.ts index 2c178a0c9..73e5043dd 100644 --- a/packages/commands/src/commands/token-plan/create-key.ts +++ b/packages/commands/src/commands/token-plan/create-key.ts @@ -56,7 +56,7 @@ export default defineCommand({ if (settings.dryRun) { const { endpoint, queryParams: query } = prepareTokenPlanRequest( - ctx.client.baseUrl, + ctx.client, API_PATH, queryParams, ); @@ -66,7 +66,6 @@ export default defineCommand({ const data = await callTokenPlanApi({ client: ctx.client, - baseUrl: ctx.client.baseUrl, action: API_ACTION, path: API_PATH, method: "POST", diff --git a/packages/commands/src/commands/token-plan/list-seats.ts b/packages/commands/src/commands/token-plan/list-seats.ts index 06e41f936..2fe2e6ee9 100644 --- a/packages/commands/src/commands/token-plan/list-seats.ts +++ b/packages/commands/src/commands/token-plan/list-seats.ts @@ -86,7 +86,7 @@ export default defineCommand({ if (settings.dryRun) { const { endpoint, queryParams: query } = prepareTokenPlanRequest( - ctx.client.baseUrl, + ctx.client, API_PATH, queryParams, ); @@ -96,7 +96,6 @@ export default defineCommand({ const data = await callTokenPlanApi({ client: ctx.client, - baseUrl: ctx.client.baseUrl, action: API_ACTION, path: API_PATH, method: "GET", diff --git a/packages/commands/src/commands/token-plan/utils.ts b/packages/commands/src/commands/token-plan/utils.ts index f866b9c36..a912a2b42 100644 --- a/packages/commands/src/commands/token-plan/utils.ts +++ b/packages/commands/src/commands/token-plan/utils.ts @@ -94,27 +94,25 @@ export function appendCommonQueryParams( } export function prepareTokenPlanRequest( - baseUrl: string, + client: Client, path: string, queryParams: TokenPlanQueryParams, ): { host: string; endpoint: string; queryString: string; queryParams: TokenPlanQueryParams } { const queryString = buildAcsCanonicalQuery(queryParams); - const host = modelStudioHost(baseUrl); + const host = client.resolveOpenApiHost(modelStudioHost(client.baseUrl)); const endpoint = `https://${host}${path}${queryString ? `?${queryString}` : ""}`; return { host, endpoint, queryString, queryParams }; } export async function callTokenPlanApi(opts: { client: Client; - /** Model-domain base URL (from ctx.client.baseUrl) — only used to pick the OpenAPI host region. */ - baseUrl: string; action: string; path: string; method: "GET" | "POST"; queryParams: TokenPlanQueryParams; }): Promise { - const { client, baseUrl, action, path, method, queryParams } = opts; - const { host } = prepareTokenPlanRequest(baseUrl, path, queryParams); + const { client, action, path, method, queryParams } = opts; + const host = modelStudioHost(client.baseUrl); return client.openApiQueryJson({ host, path, diff --git a/packages/commands/src/commands/workspace/init.ts b/packages/commands/src/commands/workspace/init.ts index f9496c725..eda59cffc 100644 --- a/packages/commands/src/commands/workspace/init.ts +++ b/packages/commands/src/commands/workspace/init.ts @@ -2,14 +2,13 @@ import { defineCommand, BailianError, ExitCode, - generateCLIAccessToken, - callConsoleGateway, + PRE_BAILIAN_CONTROL_HOST, + PRE_MODEL_STUDIO_HOST, effectiveConsoleGatewayConfig, + requirePreConsoleGateway, createBailianControlUser, listBailianControlWorkspaces, resetBailianControlPolicies4Agent, - type ConsoleGatewayTarget, - type FlagsDef, type CommandContext, } from "bailian-cli-core"; @@ -21,30 +20,6 @@ const API = { buyCommodity: "zeldaEasy.bailian-commerce.bill.buyPostpaidCommodity", } as const; -const FLAGS = { - accessKeyId: { - type: "string", - valueHint: "", - description: { "en-US": "Alibaba Cloud Access Key ID", "zh-CN": "阿里云 Access Key ID" }, - }, - accessKeySecret: { - type: "string", - valueHint: "", - description: { - "en-US": "Alibaba Cloud Access Key Secret", - "zh-CN": "阿里云 Access Key Secret", - }, - }, - securityToken: { - type: "string", - valueHint: "", - description: { - "en-US": "Alibaba Cloud STS Security Token (optional)", - "zh-CN": "阿里云 STS Security Token(可选)", - }, - }, -} satisfies FlagsDef; - const POLL_INTERVAL_MS = 1000; const MAX_POLL_ATTEMPTS = 20; @@ -80,15 +55,31 @@ export default defineCommand({ "en-US": "Initialize Bailian workspace and activate postpaid services", "zh-CN": "初始化百炼 Workspace 并开通后付费服务", }, - auth: "none", - usageArgs: "--access-key-id --access-key-secret [--security-token ]", - flags: FLAGS, - exampleArgs: ["--access-key-id LTAIxxxxx --access-key-secret xxxxx"], + auth: "openapi", + usageArgs: "[flags]", + exampleArgs: ["", "--access-key-id LTAIxxxxx --access-key-secret xxxxx"], async run(ctx) { - const { settings, flags } = ctx; + const { settings } = ctx; + const pre = settings.preControlPlane; + const gateway = effectiveConsoleGatewayConfig(settings); + const consoleTarget = { region: gateway.consoleRegion, site: gateway.consoleSite }; if (settings.dryRun) { + const preGateway = pre?.consoleGateway + ? requirePreConsoleGateway(pre, consoleTarget) + : undefined; ctx.output.result({ + ...(pre + ? { + environment: "pre", + endpoints: { + modelstudio_host: PRE_MODEL_STUDIO_HOST, + bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + ...(preGateway ? { console_gateway: preGateway } : {}), + }, + missing: preGateway ? [] : ["BAILIAN_PRE_CONSOLE_GATEWAY"], + } + : {}), apis: [ { step: 0, @@ -140,45 +131,14 @@ export default defineCommand({ return; } - const { accessKeyId, accessKeySecret } = flags; - if (!accessKeyId || !accessKeySecret) { - throw new BailianError( - "workspace init requires --access-key-id and --access-key-secret.", - ExitCode.USAGE, - ); + // Both domains must be routable before initSpace, OpenAPI writes, or purchases. + if (pre) { + requirePreConsoleGateway(pre, consoleTarget); + ctx.client.resolveOpenApiHost(PRE_MODEL_STUDIO_HOST); } - const securityToken = flags.securityToken || undefined; - - // Step 0: Exchange AK/SK for a temporary CLI access token used by console calls. - const gateway = effectiveConsoleGatewayConfig(settings); - const tokenResp = await generateCLIAccessToken({ - identity: ctx.identity, - settings: { ...settings, consoleRegion: gateway.consoleRegion }, - debug: (diagnostic) => ctx.output.debug(diagnostic), - baseUrl: ctx.client.baseUrl, - accessKeyId, - accessKeySecret, - securityToken, - }); - const accessToken: string | undefined = tokenResp.cliAccessToken; - if (!accessToken) { - throw new BailianError("Failed to generate CLI access token from AK/SK.", ExitCode.GENERAL); - } - - const target: ConsoleGatewayTarget = { - region: gateway.consoleRegion, - site: gateway.consoleSite, - ...(gateway.consoleSwitchAgent != null ? { switchAgent: gateway.consoleSwitchAgent } : {}), - token: accessToken, - }; - + ctx.client.resolveOpenApiHost(`bailiancontrol.${gateway.consoleRegion}.aliyuncs.com`); const callApi = (api: string, data: Record = {}) => - callConsoleGateway( - target, - settings.timeout, - { api, data }, - { debug: (diagnostic) => ctx.output.debug(diagnostic) }, - ); + ctx.client.console(api, data); // Step 1: Check login info ctx.output.info({ @@ -209,9 +169,7 @@ export default defineCommand({ debug: (diagnostic: Parameters[0]) => ctx.output.debug(diagnostic), baseUrl: ctx.client.baseUrl, regionId: gateway.consoleRegion, - accessKeyId, - accessKeySecret, - securityToken, + client: ctx.client, }; try { diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index f7034b112..c2ae54fa6 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -3,6 +3,7 @@ // entrypoint (bl / rag / …) builds its own `{ "": command }` map, so the // command paths a product exposes are a product decision, not baked in here. +export { default as authRoot } from "./commands/auth/aliyun.ts"; export { default as authLogin } from "./commands/auth/login.ts"; export { default as authStatus } from "./commands/auth/status.ts"; export { default as authLogout } from "./commands/auth/logout.ts"; diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts new file mode 100644 index 000000000..f2433ecd8 --- /dev/null +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -0,0 +1,1012 @@ +import http from "node:http"; +import { createHash } from "node:crypto"; +import { + ALIYUN_CLI_CLIENT_ID, + ALIYUN_CLI_SCOPE, + ALIYUN_OAUTH_BASE_URL, + PRE_ALIYUN_OAUTH_BASE_URL, + PRE_MODEL_STUDIO_HOST, + PRE_BAILIAN_CONTROL_HOST, + BailianError, + ExitCode, + buildSettings, + consoleCredentialKey, + httpTransport, + type AliyunOAuthProfile, + type AliyunOAuthSession, + type Identity, + type LocalizedText, + type PreControlPlane, +} from "bailian-cli-core"; +import { createOutputReporter } from "bailian-cli-runtime"; +import { enterIsolatedHome, type IsolatedHomeHandle } from "e2e/isolation"; +import { afterEach, beforeEach, expect, test, vi, type MockInstance } from "vite-plus/test"; +import authRoot, { + runAliyunOAuthLogin, + type AliyunOAuthLoginDeps, + type AliyunOAuthLoginOptions, +} from "../src/commands/auth/aliyun.ts"; + +// Direct module tests: no CLI or browser child process, actual loopback GET, mocked remote transport. +const ENDPOINTS = { + authorizationUrl: "https://authorize.oauth-test.example/authorize?channel=cli", + oauthBaseUrl: "https://tokens.oauth-test.example", + modelstudioHost: "pop.oauth-test.example", + consoleGateway: "https://console.oauth-test.example", + bailiancontrolHost: "control.oauth-test.example", +}; +const DEFAULT_ENDPOINTS = { + modelstudioHost: "modelstudio.cn-beijing.aliyuncs.com", + consoleGateway: "https://bailian-cs.console.aliyun.com", +}; +const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; +const SECRETS = { + code: "test-authorization-code-secret", + accessToken: "test-oauth-access-token-secret", + refreshToken: "test-oauth-refresh-token-secret", + accessKeyId: "test-sts-access-key-id-secret", + accessKeySecret: "test-sts-access-key-secret-secret", + securityToken: "test-sts-security-token-secret", + cliAccessToken: "test-cli-access-token-secret", +}; +type Stage = "token" | "sts" | "generate" | "gateway"; +interface RecordedRequest { + url: URL; + init: RequestInit; +} +let isolation: IsolatedHomeHandle; +let requests: RecordedRequest[]; +let failStage: Stage | undefined; +let revokeFails: boolean; +let stsExpiresAt: number; +let accessTokenIssuedAt: number; +let activeProbes: { controller: AbortController; outcome: Promise }[]; +let fetchMock: MockInstance; +let unexpectedStdout: MockInstance; +let unexpectedStderr: MockInstance; + +function deferred() { + let resolveValue!: (value: Value) => void; + const promise = new Promise((resolve) => { + resolveValue = resolve; + }); + return { promise, resolve: resolveValue }; +} + +function stringBody(body: RequestInit["body"]): string { + if (typeof body !== "string") throw new Error("Expected a string request body"); + return body; +} + +function jsonResponse(data: unknown, status = 200): Response { + return new Response(JSON.stringify(data), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +beforeEach(() => { + isolation = enterIsolatedHome(); + requests = []; + activeProbes = []; + failStage = undefined; + revokeFails = false; + stsExpiresAt = Date.now() + 3600_000; + accessTokenIssuedAt = 0; + // Injected writers own module output; accidental global writes are a regression. + unexpectedStdout = vi.spyOn(process.stdout, "write").mockReturnValue(true); + unexpectedStderr = vi.spyOn(process.stderr, "write").mockReturnValue(true); + fetchMock = vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : input.toString()); + requests.push({ url, init }); + const isOAuth = + [ENDPOINTS.oauthBaseUrl, PRE_ALIYUN_OAUTH_BASE_URL].includes(url.origin) && !url.search; + if (isOAuth && url.pathname === "/v1/revoke") { + return new Response(null, { status: revokeFails ? 503 : 200 }); + } + let stage: Stage; + if (isOAuth && url.pathname === "/v1/token") stage = "token"; + else if (isOAuth && url.pathname === "/v1/exchange") stage = "sts"; + else if ( + [ENDPOINTS.modelstudioHost, DEFAULT_ENDPOINTS.modelstudioHost, PRE_MODEL_STUDIO_HOST].some( + (hostname) => url.href === `https://${hostname}/modelstudio/cli/generateAccessToken`, + ) + ) + stage = "generate"; + else if ( + [ENDPOINTS.consoleGateway, DEFAULT_ENDPOINTS.consoleGateway, PRE_CONSOLE_GATEWAY].includes( + url.origin, + ) && + url.pathname === "/cli/api.json" + ) + stage = "gateway"; + else throw new Error(`Unexpected mocked endpoint: ${url.origin}${url.pathname}`); + if (stage === failStage) { + if (stage === "gateway") + return jsonResponse({ + data: { + success: false, + errorCode: "ValidationDenied", + errorMsg: `Denied ${SECRETS.cliAccessToken}`, + requestId: "mock-request-id", + }, + }); + const tokenForm = stage === "token" ? new URLSearchParams(stringBody(init.body)) : undefined; + const echoedSecrets = tokenForm + ? `${tokenForm.get("code")} ${tokenForm.get("code_verifier")}` + : stage === "sts" + ? SECRETS.accessToken + : `${SECRETS.accessKeyId} ${SECRETS.accessKeySecret} ${SECRETS.securityToken}`; + return jsonResponse( + { Success: false, Code: "MockDenied", Message: `Denied ${echoedSecrets}` }, + 403, + ); + } + switch (stage) { + case "token": + accessTokenIssuedAt = Date.now(); + return jsonResponse({ + access_token: SECRETS.accessToken, + refresh_token: SECRETS.refreshToken, + expires_in: 1800, + token_type: "Bearer", + scope: ALIYUN_CLI_SCOPE, + }); + case "sts": + return jsonResponse({ + AccessKeyId: SECRETS.accessKeyId, + AccessKeySecret: SECRETS.accessKeySecret, + SecurityToken: SECRETS.securityToken, + Expiration: new Date(stsExpiresAt).toISOString(), + }); + case "generate": + return jsonResponse({ cliAccessToken: SECRETS.cliAccessToken }); + case "gateway": + return jsonResponse({ data: { success: true } }); + } + }); +}); + +afterEach(async () => { + for (const probe of activeProbes) probe.controller.abort(); + await Promise.all(activeProbes.map((probe) => probe.outcome)); + try { + expect(unexpectedStdout).not.toHaveBeenCalled(); + expect(unexpectedStderr).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + vi.restoreAllMocks(); + isolation.restore(); + } +}); + +function localizer(language: "en-US" | "zh-CN") { + return (text: LocalizedText) => (typeof text === "string" ? text : text[language]); +} + +function launch( + options: AliyunOAuthLoginOptions = {}, + settingsOptions: { + dryRun?: boolean; + output?: "text" | "json"; + language?: "en-US" | "zh-CN"; + previous?: AliyunOAuthProfile; + quiet?: boolean; + verbose?: boolean; + omitEndpoints?: boolean; + preControlPlane?: PreControlPlane; + } = {}, +) { + const stdout: string[] = []; + const stderr: string[] = []; + const settings = { + ...buildSettings({ + flags: { + output: settingsOptions.output ?? "json", + dryRun: !!settingsOptions.dryRun, + quiet: !!settingsOptions.quiet, + verbose: !!settingsOptions.verbose, + }, + file: {}, + env: {}, + preControlPlane: settingsOptions.preControlPlane, + }), + configName: "oauth-test", + }; + const localize = localizer(settingsOptions.language ?? "en-US"); + const reporter = createOutputReporter({ + settings, + localize, + stdout: { write: (text) => stdout.push(text) }, + stderr: { write: (text) => stderr.push(text) }, + }); + const describe = vi.fn(() => + settingsOptions.previous ? { aliyunOAuth: settingsOptions.previous } : {}, + ); + const save = vi + .fn< + ( + profile: Omit, + session: AliyunOAuthSession, + ) => Promise + >() + .mockResolvedValue(undefined); + const controller = new AbortController(); + const url = deferred(); + const browser = vi.fn<(authUrl: string) => void | Promise>().mockResolvedValue(undefined); + const deps: AliyunOAuthLoginDeps = { + identity: { + binName: "bl", + version: "test", + clientName: "oauth-test", + npmPackage: "bailian-cli", + } as Identity, + settings, + localize, + output: reporter.output, + writeStderr: (text) => { + stderr.push(text); + }, + authStore: { describe, loginAliyun: save }, + onAuthUrl: url.resolve, + openBrowser: browser, + }; + const signal = options.signal + ? AbortSignal.any([controller.signal, options.signal]) + : controller.signal; + const resolvedOptions = { + ...(settingsOptions.preControlPlane ? {} : { clientId: ALIYUN_CLI_CLIENT_ID }), + ...(settingsOptions.omitEndpoints ? {} : ENDPOINTS), + callbackTimeoutMs: 1000, + ...options, + signal, + }; + const signalCounts = { + SIGINT: process.listenerCount("SIGINT"), + SIGTERM: process.listenerCount("SIGTERM"), + }; + const outcome = runAliyunOAuthLogin(deps, resolvedOptions).then( + () => undefined, + (error: unknown) => error, + ); + const probe = { + deps, + options: resolvedOptions, + controller, + browser, + save, + describe, + reporter, + stdout, + stderr, + authUrl: url.promise, + outcome, + signalCounts, + }; + activeProbes.push(probe); + return probe; +} + +function callbackUrl( + authUrl: string, + params: Record = { code: SECRETS.code }, +): URL { + const authorization = new URL(authUrl); + const redirectUri = authorization.searchParams.get("redirect_uri"); + if (!redirectUri) throw new Error("Missing redirect_uri"); + const callback = new URL(redirectUri); + callback.searchParams.set("state", authorization.searchParams.get("state")!); + for (const [name, value] of Object.entries(params)) callback.searchParams.set(name, value); + return callback; +} + +function localRequest( + url: URL, + method = "GET", +): Promise<{ status: number; body: string; headers: http.IncomingHttpHeaders }> { + if (url.hostname !== "127.0.0.1" || url.protocol !== "http:") + throw new Error("Only actual loopback callbacks are allowed"); + return new Promise((resolve, reject) => { + const request = http.request( + { + host: "127.0.0.1", + port: Number(url.port), + path: url.pathname + url.search, + method, + agent: false, + headers: { Connection: "close" }, + }, + (response) => { + const chunks: Buffer[] = []; + response.on("data", (chunk: Buffer) => chunks.push(chunk)); + response.on("end", () => + resolve({ + status: response.statusCode ?? 0, + body: Buffer.concat(chunks).toString("utf8"), + headers: response.headers, + }), + ); + response.on("error", reject); + }, + ); + request.on("error", reject); + request.end(); + }); +} + +function assertNoSecrets(probe: ReturnType, extra: string[] = []) { + const output = [...probe.stdout, ...probe.stderr].join(""); + for (const secret of [...Object.values(SECRETS), ...extra]) expect(output).not.toContain(secret); +} + +function assertSignalCleanup(probe: ReturnType) { + expect(process.listenerCount("SIGINT")).toBe(probe.signalCounts.SIGINT); + expect(process.listenerCount("SIGTERM")).toBe(probe.signalCounts.SIGTERM); +} + +async function finish(probe: ReturnType) { + const authUrl = await probe.authUrl; + const callback = callbackUrl(authUrl); + const result = await localRequest(callback); + expect(result.status).toBe(200); + const error = await probe.outcome; + if (error !== undefined) throw error; + return { authUrl, callback, result }; +} + +test("根命令声明必填 aliyun 登录方式与双语 flags,不改变旧登录命令", () => { + expect(authRoot.auth).toBe("none"); + expect(authRoot.flags!.login).toMatchObject({ + type: "string", + required: true, + choices: ["aliyun"], + }); + expect(authRoot.flags!.consoleRegion).toMatchObject({ choices: ["cn-beijing"] }); + for (const definition of Object.values(authRoot.flags!)) + expect(definition.description).toEqual({ + "en-US": expect.any(String), + "zh-CN": expect.any(String), + }); + expect(authRoot.flags!).not.toHaveProperty("device"); + expect(authRoot.flags!).not.toHaveProperty("tokenStdin"); +}); + +test("完整 OAuth→STS→显式 POP→显式网关→保存链路使用 PKCE、随机 loopback 端口且不猜 Console TTL", async () => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const createServer = vi.spyOn(http, "createServer"); + const probe = launch({}, { quiet: true, verbose: true }); + const { authUrl, callback, result } = await finish(probe); + expect(listen).toHaveBeenCalledWith( + { port: 0, host: "127.0.0.1", exclusive: true }, + expect.any(Function), + ); + expect(Number(callback.port)).toBeGreaterThan(0); + expect(callback.pathname).toBe("/oauth/callback"); + expect(new URL(authUrl).origin).toBe(new URL(ENDPOINTS.authorizationUrl).origin); + const query = new URL(authUrl).searchParams; + expect(query.get("response_type")).toBe("code"); + expect(query.get("client_id")).toBe(ALIYUN_CLI_CLIENT_ID); + expect(query.get("scope")).toBe(ALIYUN_CLI_SCOPE); + expect(query.get("channel")).toBe("cli"); + expect(query.get("state")).toMatch(/^[A-Za-z0-9_-]{43}$/u); + expect(query.get("code_challenge_method")).toBe("S256"); + expect(result.headers["cache-control"]).toBe("no-store"); + expect(result.headers["referrer-policy"]).toBe("no-referrer"); + expect(result.body).not.toContain(SECRETS.code); + expect(requests.map((request) => request.url.pathname)).toEqual([ + "/v1/token", + "/v1/exchange", + "/modelstudio/cli/generateAccessToken", + "/cli/api.json", + ]); + for (const request of requests) expect(request.init.method).toBe("POST"); + const token = requests[0]!; + expect(new Headers(token.init.headers).get("content-type")).toBe( + "application/x-www-form-urlencoded", + ); + expect(token.init.redirect).toBe("error"); + const form = new URLSearchParams(stringBody(token.init.body)); + const verifier = form.get("code_verifier")!; + expect(verifier).toMatch(/^[A-Za-z0-9_-]{43}$/u); + expect(query.get("code_challenge")).toBe( + createHash("sha256").update(verifier, "ascii").digest("base64url"), + ); + expect(Object.fromEntries(form)).toEqual({ + grant_type: "authorization_code", + client_id: ALIYUN_CLI_CLIENT_ID, + code: SECRETS.code, + redirect_uri: `http://127.0.0.1:${callback.port}/oauth/callback`, + code_verifier: verifier, + }); + const exchange = requests[1]!; + expect(new Headers(exchange.init.headers).get("authorization")).toBe( + `Bearer ${SECRETS.accessToken}`, + ); + expect(exchange.init.body).toBeUndefined(); + expect(exchange.init.redirect).toBe("error"); + const generate = requests[2]!; + const generateHeaders = new Headers(generate.init.headers); + expect(generate.url.host).toBe(ENDPOINTS.modelstudioHost); + expect(generateHeaders.get("x-acs-action")).toBe("GenerateCLIAccessToken"); + expect(generateHeaders.get("x-acs-version")).toBe("2026-02-10"); + expect(generateHeaders.get("x-acs-security-token")).toBe(SECRETS.securityToken); + expect(generateHeaders.get("authorization")).toContain(`Credential=${SECRETS.accessKeyId}`); + expect(generateHeaders.get("authorization")).not.toContain(SECRETS.accessKeySecret); + expect(generate.init.body).toBeUndefined(); + const gateway = requests[3]!; + expect(gateway.url.origin).toBe(ENDPOINTS.consoleGateway); + expect(gateway.url.searchParams.get("api")).toBe( + "zeldaEasy.cornerstone-portal.cs-console.loginInfo", + ); + expect(gateway.url.searchParams.get("product")).toBe("sfm_bailian"); + expect(gateway.url.searchParams.get("action")).toBe("BroadScopeAspnGateway"); + expect(gateway.init.redirect).toBe("error"); + expect(new Headers(gateway.init.headers).get("authorization")).toBe( + `Bearer ${SECRETS.cliAccessToken}`, + ); + const gatewayForm = new URLSearchParams(stringBody(gateway.init.body)); + expect(gatewayForm.get("region")).toBe("cn-beijing"); + expect(JSON.parse(gatewayForm.get("params")!)).toEqual({ + Api: "zeldaEasy.cornerstone-portal.cs-console.loginInfo", + V: "1.0", + Data: { + cornerstoneParam: { + protocol: "V2", + console: "ONE_CONSOLE", + productCode: "p_efm", + switchUserType: 3, + consoleSite: "BAILIAN_ALIYUN", + }, + }, + }); + expect(probe.save).toHaveBeenCalledTimes(1); + const [profile, session] = probe.save.mock.calls[0]!; + expect(profile).toEqual({ + client_id: ALIYUN_CLI_CLIENT_ID, + scope: ALIYUN_CLI_SCOPE, + authorization_url: ENDPOINTS.authorizationUrl, + oauth_base_url: ENDPOINTS.oauthBaseUrl, + modelstudio_host: ENDPOINTS.modelstudioHost, + bailiancontrol_host: ENDPOINTS.bailiancontrolHost, + console_gateway: ENDPOINTS.consoleGateway, + console_region: "cn-beijing", + console_enabled: true, + openapi_enabled: true, + access_token_expires_at: session.accessTokenExpiresAt, + sts_expires_at: stsExpiresAt, + }); + expect(session.accessToken).toBe(SECRETS.accessToken); + expect(session.refreshToken).toBe(SECRETS.refreshToken); + expect(session.accessTokenExpiresAt).toBeGreaterThanOrEqual(accessTokenIssuedAt + 1800_000); + expect(session.accessTokenExpiresAt).toBeLessThanOrEqual(Date.now() + 1800_000); + expect(session.sts).toEqual({ + accessKeyId: SECRETS.accessKeyId, + accessKeySecret: SECRETS.accessKeySecret, + securityToken: SECRETS.securityToken, + expiresAt: stsExpiresAt, + }); + expect(session.consoleTokens).toEqual({ + [consoleCredentialKey({ + region: "cn-beijing", + site: "domestic", + gateway: ENDPOINTS.consoleGateway, + })]: { token: SECRETS.cliAccessToken }, + }); + expect(JSON.parse(probe.stdout.join(""))).toEqual({ + authenticated: true, + method: "aliyun", + config: "oauth-test", + console: true, + openapi: true, + }); + expect(probe.stderr.join("")).toContain(authUrl); + expect(probe.stderr.join("")).toContain("Waiting for the local OAuth callback"); + assertNoSecrets(probe, [verifier]); + assertSignalCleanup(probe); + expect(createServer.mock.results[0]!.value.address()).toBeNull(); + await expect(localRequest(callback)).rejects.toMatchObject({ code: "ECONNREFUSED" }); +}); + +test.each(["text", "json"] as const)( + "双语成功结果仅含安全状态,登录链接仍写 stderr (%s)", + async (output) => { + const probe = launch({}, { output, language: "zh-CN" }); + await finish(probe); + expect(probe.stderr.join("")).toContain("请在本机浏览器中打开"); + expect(probe.stderr.join("")).toContain("正在等待本机 OAuth 回调"); + if (output === "text") + expect(probe.stdout.join("")).toBe( + "阿里云 OAuth 登录成功(配置:oauth-test;console:true;openapi:true)。\n", + ); + else expect(JSON.parse(probe.stdout.join("")).authenticated).toBe(true); + assertNoSecrets(probe); + }, +); + +test("错误或重复 state、缺失或重复 code 均拒绝并继续等待,有效 state 的拒绝不能被错误 state 伪造", async () => { + const probe = launch({ noBrowser: true }); + const authUrl = await probe.authUrl; + const callback = callbackUrl(authUrl); + const malformed: URL[] = []; + const wrongState = new URL(callback); + wrongState.searchParams.set("state", "wrong-state"); + wrongState.searchParams.set("error", "access_denied"); + malformed.push(wrongState); + const absentState = new URL(callback); + absentState.searchParams.delete("state"); + malformed.push(absentState); + const duplicateState = new URL(callback); + duplicateState.searchParams.append("state", duplicateState.searchParams.get("state")!); + malformed.push(duplicateState); + const emptyCode = new URL(callback); + emptyCode.searchParams.set("code", " "); + malformed.push(emptyCode); + const duplicateCode = new URL(callback); + duplicateCode.searchParams.append("code", SECRETS.code); + malformed.push(duplicateCode); + for (const invalid of malformed) expect((await localRequest(invalid)).status).toBe(400); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + expect((await localRequest(callback)).status).toBe(200); + expect(await probe.outcome).toBeUndefined(); + expect(probe.browser).not.toHaveBeenCalled(); + assertNoSecrets(probe); +}); + +test("回调只接受 /oauth/callback GET,拒绝 POST/OPTIONS 与其它路径而不消费登录", async () => { + const probe = launch(); + const callback = callbackUrl(await probe.authUrl); + for (const method of ["POST", "OPTIONS"]) { + const result = await localRequest(callback, method); + expect(result.status).toBe(405); + expect(result.headers.allow).toBe("GET"); + } + for (const pathname of ["/", "/callback", "/oauth/callback/"]) { + const otherPath = new URL(callback); + otherPath.pathname = pathname; + expect((await localRequest(otherPath)).status).toBe(404); + } + expect(fetchMock).not.toHaveBeenCalled(); + await finish(probe); +}); + +test("有效 state 的 OAuth 拒绝结束失败,error_description 不回显且不请求或保存", async () => { + const probe = launch(); + const callback = callbackUrl(await probe.authUrl, { + error: "access_denied", + error_description: SECRETS.refreshToken, + }); + expect((await localRequest(callback)).status).toBe(400); + const error = await probe.outcome; + expect(error).toBeInstanceOf(BailianError); + expect(error).toMatchObject({ exitCode: ExitCode.GENERAL }); + probe.reporter.error(error); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + assertNoSecrets(probe); + assertSignalCleanup(probe); +}); + +test.each(["hang", "reject", "throw"] as const)( + "浏览器启动%s不阻止本机回调与清理", + async (behavior) => { + const probe = launch(); + probe.browser.mockImplementation(() => { + if (behavior === "throw") throw new Error(SECRETS.refreshToken); + if (behavior === "reject") return Promise.reject(new Error(SECRETS.refreshToken)); + return new Promise(() => {}); + }); + await finish(probe); + expect(probe.browser).toHaveBeenCalledTimes(1); + if (behavior !== "hang") expect(probe.stderr.join("")).toContain("Open the URL above manually"); + assertNoSecrets(probe); + assertSignalCleanup(probe); + }, +); + +test("打开浏览器时即刻回调不会漏掉完成事件", async () => { + const probe = launch(); + const browserCallback = deferred(); + probe.browser.mockImplementation(async (authUrl) => { + browserCallback.resolve((await localRequest(callbackUrl(authUrl))).status); + }); + expect(await probe.outcome).toBeUndefined(); + expect(await browserCallback.promise).toBe(200); + expect(probe.save).toHaveBeenCalledTimes(1); +}); + +test("真实短超时关闭服务器且不产生请求、保存或遗留信号监听器", async () => { + const probe = launch({ callbackTimeoutMs: 20, noBrowser: true }); + const callback = callbackUrl(await probe.authUrl); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.TIMEOUT }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + assertSignalCleanup(probe); + await expect(localRequest(callback)).rejects.toMatchObject({ code: "ECONNREFUSED" }); +}); + +test("受控时间推进覆盖超时边界并清除本次定时器", async () => { + vi.useFakeTimers(); + const probe = launch({ callbackTimeoutMs: 100, noBrowser: true }); + await probe.authUrl; + await vi.advanceTimersByTimeAsync(99); + expect(probe.save).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(1); + await vi.advanceTimersByTimeAsync(1); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.TIMEOUT }); + expect(vi.getTimerCount()).toBe(0); + assertSignalCleanup(probe); +}); + +test.each(["abort", "SIGINT", "SIGTERM"] as const)( + "等待回调期间%s取消并清理服务器", + async (kind) => { + const probe = launch({ noBrowser: true }); + const callback = callbackUrl(await probe.authUrl); + if (kind === "abort") probe.controller.abort(new Error(SECRETS.accessToken)); + else { + // Invoke only this module's new handler; never send a real OS signal to the test worker. + const handler = process.listeners(kind).at(-1)!; + Reflect.apply(handler, process, []); + } + const error = await probe.outcome; + expect(error).toMatchObject({ exitCode: ExitCode.INTERRUPTED }); + probe.reporter.error(error); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + assertNoSecrets(probe); + assertSignalCleanup(probe); + await expect(localRequest(callback)).rejects.toMatchObject({ code: "ECONNREFUSED" }); + }, +); + +test("预先取消的信号在 proof/监听/浏览器/网络之前失败", async () => { + const signal = AbortSignal.abort(); + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch({ signal }); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.INTERRUPTED }); + expect(listen).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + assertSignalCleanup(probe); +}); + +test.each(["token", "sts", "generate", "gateway"] as const)( + "%s下游失败不保存 Profile;已获得 RT 时尽力撤销且不泄漏凭据", + async (stage) => { + failStage = stage; + const probe = launch(); + expect((await localRequest(callbackUrl(await probe.authUrl))).status).toBe(200); + const error = await probe.outcome; + expect(error).toBeInstanceOf(BailianError); + expect(error).toMatchObject({ exitCode: ExitCode.GENERAL }); + expect(probe.save).not.toHaveBeenCalled(); + expect(probe.stdout).toEqual([]); + const revocations = requests.filter((request) => request.url.pathname === "/v1/revoke"); + expect(revocations).toHaveLength(stage === "token" ? 0 : 1); + if (stage !== "token") { + expect( + Object.fromEntries(new URLSearchParams(stringBody(revocations[0]!.init.body))), + ).toEqual({ client_id: ALIYUN_CLI_CLIENT_ID, token: SECRETS.refreshToken }); + expect(revocations[0]!.init.redirect).toBe("error"); + } + if (stage === "gateway") + expect(error).toMatchObject({ + api: { apiCode: "ValidationDenied", requestId: "mock-request-id" }, + }); + probe.reporter.error(error); + const requestPaths = [ + "/v1/token", + "/v1/exchange", + "/modelstudio/cli/generateAccessToken", + "/cli/api.json", + ]; + expect( + requests + .filter((request) => request.url.pathname !== "/v1/revoke") + .map((request) => request.url.pathname), + ).toEqual(requestPaths.slice(0, ["token", "sts", "generate", "gateway"].indexOf(stage) + 1)); + assertNoSecrets(probe); + assertSignalCleanup(probe); + }, +); + +test.each(["network", "timeout"] as const)( + "传输%s错误保留 runtime 分类且脱敏 cause", + async (kind) => { + const probe = launch(); + const cause = Object.assign(new Error(`lookup ${SECRETS.code}`), { code: "ENOTFOUND" }); + const failure = + kind === "network" + ? new TypeError("fetch failed", { cause }) + : Object.assign(new Error(`request timed out ${SECRETS.code}`), { name: "TimeoutError" }); + fetchMock.mockRejectedValueOnce(failure); + await localRequest(callbackUrl(await probe.authUrl)); + const error = await probe.outcome; + expect(probe.reporter.error(error)).toBe( + kind === "network" ? ExitCode.NETWORK : ExitCode.TIMEOUT, + ); + expect(probe.save).not.toHaveBeenCalled(); + assertNoSecrets(probe); + assertSignalCleanup(probe); + }, +); + +test("保存失败时撤销新 RT,撤销失败不掩盖主错误或打印凭据", async () => { + revokeFails = true; + const probe = launch(); + probe.save.mockRejectedValue( + new BailianError( + `Store failed ${SECRETS.refreshToken}`, + ExitCode.GENERAL, + `Do not expose ${SECRETS.accessKeySecret}`, + { cause: new Error(SECRETS.securityToken) }, + ), + ); + await localRequest(callbackUrl(await probe.authUrl)); + const error = await probe.outcome; + expect(error).toMatchObject({ + message: "Store failed [REDACTED]", + hint: "Do not expose [REDACTED]", + }); + expect(String(error)).not.toContain("revocation"); + probe.reporter.error(error); + expect(probe.stdout).toEqual([]); + expect(requests.at(-1)!.url.pathname).toBe("/v1/revoke"); + assertNoSecrets(probe); + assertSignalCleanup(probe); +}); + +test("下游阶段取消不保存,并撤销已经获得的 RT", async () => { + const probe = launch(); + fetchMock.mockImplementationOnce(async () => { + probe.controller.abort(); + return jsonResponse({ + access_token: SECRETS.accessToken, + refresh_token: SECRETS.refreshToken, + expires_in: 1800, + }); + }); + await localRequest(callbackUrl(await probe.authUrl)); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.INTERRUPTED }); + expect(probe.save).not.toHaveBeenCalled(); + expect(requests.map((request) => request.url.pathname)).toEqual(["/v1/revoke"]); + assertSignalCleanup(probe); +}); + +test.each([false, true])( + "既有 OAuth 端点优先于默认值,显式端点覆盖优先于 Profile (%s)", + async (overrideEndpoints) => { + const previous: AliyunOAuthProfile = { + client_id: "stored-client", + scope: "openid", + authorization_url: ENDPOINTS.authorizationUrl, + oauth_base_url: ENDPOINTS.oauthBaseUrl, + modelstudio_host: ENDPOINTS.modelstudioHost, + console_gateway: ENDPOINTS.consoleGateway, + console_region: "cn-beijing", + session_ref: "test-session-reference", + console_enabled: false, + openapi_enabled: false, + }; + const probe = launch( + { + clientId: "override-client", + scope: "openid", + ...(overrideEndpoints ? DEFAULT_ENDPOINTS : {}), + }, + { previous, omitEndpoints: true }, + ); + const authUrl = await probe.authUrl; + expect(new URL(authUrl).searchParams.get("client_id")).toBe("override-client"); + expect(new URL(authUrl).searchParams.get("scope")).toBe("openid"); + await finish(probe); + expect(probe.save.mock.calls[0]![0]).toMatchObject({ + client_id: "override-client", + scope: "openid", + modelstudio_host: overrideEndpoints + ? DEFAULT_ENDPOINTS.modelstudioHost + : ENDPOINTS.modelstudioHost, + console_gateway: overrideEndpoints + ? DEFAULT_ENDPOINTS.consoleGateway + : ENDPOINTS.consoleGateway, + console_enabled: true, + openapi_enabled: true, + }); + expect(new URLSearchParams(stringBody(requests[0]!.init.body)).get("client_id")).toBe( + "override-client", + ); + expect(requests[2]!.url.host).toBe( + overrideEndpoints ? DEFAULT_ENDPOINTS.modelstudioHost : ENDPOINTS.modelstudioHost, + ); + expect(requests[3]!.url.origin).toBe( + overrideEndpoints ? DEFAULT_ENDPOINTS.consoleGateway : ENDPOINTS.consoleGateway, + ); + expect(probe.describe).toHaveBeenCalledTimes(1); + }, +); + +test.each([ + { authorizationUrl: "http://external.example/authorize" }, + { authorizationUrl: "https://user:secret@authorize.example/authorize" }, + { authorizationUrl: "https://authorize.example/authorize#fragment" }, + { authorizationUrl: "not-a-url" }, + { oauthBaseUrl: "http://external.example" }, + { oauthBaseUrl: "https://tokens.example/path" }, + { oauthBaseUrl: "https://tokens.example/?query=1" }, + { consoleGateway: "https://console.example/cli/api.json" }, + { consoleGateway: "http://external.example" }, + { consoleGateway: "" }, + { modelstudioHost: "" }, + { modelstudioHost: "https://pop.example" }, + { modelstudioHost: "pop.example/path" }, + { bailiancontrolHost: "user@control.example" }, + { consoleRegion: "ap-southeast-1" }, + { clientId: " " }, + { scope: " " }, +])("非法 URL/hostname/地域/空覆盖在监听和请求前拒绝:%j", async (options) => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch(options); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); + expect(listen).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + +test("首次登录缺授权地址在监听和请求前拒绝", async () => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch({ authorizationUrl: undefined }); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); + expect(listen).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + +test.each([ + { modelstudioHost: undefined }, + { consoleGateway: undefined }, + { modelstudioHost: undefined, consoleGateway: undefined }, +])("首次登录省略 POP/网关复用既有默认值,单独覆盖仍生效:%j", async (options) => { + const probe = launch(options); + await finish(probe); + const modelstudioHost = + "modelstudioHost" in options ? DEFAULT_ENDPOINTS.modelstudioHost : ENDPOINTS.modelstudioHost; + const consoleGateway = + "consoleGateway" in options ? DEFAULT_ENDPOINTS.consoleGateway : ENDPOINTS.consoleGateway; + expect(requests.map((request) => request.url.pathname)).toEqual([ + "/v1/token", + "/v1/exchange", + "/modelstudio/cli/generateAccessToken", + "/cli/api.json", + ]); + expect(requests[2]!.url.host).toBe(modelstudioHost); + expect(new Headers(requests[2]!.init.headers).get("x-acs-security-token")).toBe( + SECRETS.securityToken, + ); + expect(requests[3]!.url.origin).toBe(consoleGateway); + expect(new Headers(requests[3]!.init.headers).get("authorization")).toBe( + `Bearer ${SECRETS.cliAccessToken}`, + ); + expect(probe.save).toHaveBeenCalledTimes(1); + const [profile, session] = probe.save.mock.calls[0]!; + expect(profile).toMatchObject({ + modelstudio_host: modelstudioHost, + console_gateway: consoleGateway, + }); + expect(session.consoleTokens).toEqual({ + [consoleCredentialKey({ region: "cn-beijing", site: "domestic", gateway: consoleGateway })]: { + token: SECRETS.cliAccessToken, + }, + }); + assertNoSecrets(probe); + assertSignalCleanup(probe); +}); + +test.each([true, false])( + "dry-run 零秘密读取/监听/浏览器/请求/保存,允许缺端点 (%s)", + async (omitEndpoints) => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch({}, { dryRun: true, omitEndpoints }); + expect(await probe.outcome).toBeUndefined(); + expect(probe.describe).not.toHaveBeenCalled(); + expect(listen).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + expect(probe.stderr).toEqual([]); + const data = JSON.parse(probe.stdout.join("")); + expect(data.method).toBe("aliyun"); + expect(data.missing).toEqual(omitEndpoints ? ["--authorization-url"] : []); + expect(data.plan.modelstudio_host).toBe( + omitEndpoints ? DEFAULT_ENDPOINTS.modelstudioHost : ENDPOINTS.modelstudioHost, + ); + expect(data.plan.console_gateway).toBe( + omitEndpoints ? DEFAULT_ENDPOINTS.consoleGateway : ENDPOINTS.consoleGateway, + ); + expect(data.plan.client_id).toBe(ALIYUN_CLI_CLIENT_ID); + expect(data.plan.scope).toBe(ALIYUN_CLI_SCOPE); + expect(data.plan.oauth_base_url).toBe( + omitEndpoints ? ALIYUN_OAUTH_BASE_URL : ENDPOINTS.oauthBaseUrl, + ); + assertNoSecrets(probe); + assertSignalCleanup(probe); + }, +); + +test("预发 OAuth 首次登录预览列出预设端点和未确认的 Console 网关", async () => { + const probe = launch({}, { dryRun: true, omitEndpoints: true, preControlPlane: {} }); + expect(await probe.outcome).toBeUndefined(); + expect(JSON.parse(probe.stdout.join(""))).toMatchObject({ + environment: "pre", + missing: ["BAILIAN_PRE_CONSOLE_GATEWAY"], + plan: { + oauth_base_url: PRE_ALIYUN_OAUTH_BASE_URL, + modelstudio_host: PRE_MODEL_STUDIO_HOST, + bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + }, + }); + expect(probe.describe).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +test("预发 OAuth 登录绑定预设端点,不请求线上网关", async () => { + const probe = launch( + {}, + { omitEndpoints: true, preControlPlane: { consoleGateway: PRE_CONSOLE_GATEWAY } }, + ); + await finish(probe); + expect(requests.map(({ url }) => url.origin)).toEqual([ + PRE_ALIYUN_OAUTH_BASE_URL, + PRE_ALIYUN_OAUTH_BASE_URL, + `https://${PRE_MODEL_STUDIO_HOST}`, + PRE_CONSOLE_GATEWAY, + ]); + expect(probe.save).toHaveBeenCalledWith( + expect.objectContaining({ + modelstudio_host: PRE_MODEL_STUDIO_HOST, + console_gateway: PRE_CONSOLE_GATEWAY, + bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + }), + expect.any(Object), + ); + assertNoSecrets(probe); +}); + +test.each([{}, { consoleGateway: PRE_CONSOLE_GATEWAY }])( + "预发预检拒绝缺失网关或线上 OAuth 覆盖,零请求、零落盘 (%j)", + async (preControlPlane) => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch( + { oauthBaseUrl: ALIYUN_OAUTH_BASE_URL }, + { omitEndpoints: true, preControlPlane }, + ); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); + expect(listen).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + }, +); + +test("dry-run 只对 HTTP loopback 端点放行,拒绝外部 HTTP", async () => { + const probe = launch( + { + authorizationUrl: "http://127.0.0.1:43210/authorize", + oauthBaseUrl: "http://localhost:43211", + consoleGateway: "http://[::1]:43212", + }, + { dryRun: true }, + ); + expect(await probe.outcome).toBeUndefined(); + expect(JSON.parse(probe.stdout.join("")).plan).toMatchObject({ + authorization_url: "http://127.0.0.1:43210/authorize", + oauth_base_url: "http://localhost:43211", + console_gateway: "http://[::1]:43212", + }); + const invalid = launch({ consoleGateway: "http://external.example" }, { dryRun: true }); + expect(await invalid.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); + expect(fetchMock).not.toHaveBeenCalled(); +}); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index 3543ab7d4..661a4b208 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -61,6 +61,63 @@ afterAll(async () => { }); describe("e2e: auth", () => { + test("auth 父命令暴露 aliyun 登录且保留既有子命令", async () => { + const result = await runCommandHelp(AUTH_ROUTES, ["auth", "--help"]); + expect(result.exitCode, result.stderr).toBe(0); + for (const flag of [ + "--login", + "--authorization-url", + "--modelstudio-host", + "--console-gateway", + ]) + expect(result.stderr).toContain(flag); + for (const command of ["auth login", "auth status", "auth logout"]) + expect(result.stderr).toContain(command); + }); + + test("aliyun dry-run 仅返回配置计划与缺少的端点", async () => { + const result = await runCommandInProcess(AUTH_ROUTES, [ + "auth", + "--login", + "aliyun", + "--dry-run", + "--output", + "json", + ]); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + method: string; + plan: { + client_id: string; + scope: string; + modelstudio_host: string; + console_gateway: string; + }; + missing: string[]; + }>(result.stdout); + expect(data.method).toBe("aliyun"); + expect(data.plan.client_id).toBeUndefined(); + expect(data.plan.scope).toBe("openid /internal/bailian/cli"); + expect(data.plan.modelstudio_host).toBe("modelstudio.cn-beijing.aliyuncs.com"); + expect(data.plan.console_gateway).toBe("https://bailian-cs.console.aliyun.com"); + expect(data.missing).toEqual(["--authorization-url", "--client-id"]); + }); + + test("aliyun 首次登录未给授权地址时在授权前失败", async () => { + const result = await runCommandInProcess(AUTH_ROUTES, [ + "auth", + "--login", + "aliyun", + "--output", + "json", + ]); + expect(result.exitCode).toBe(2); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("--authorization-url"); + expect(result.stderr).not.toContain("--modelstudio-host"); + expect(result.stderr).not.toContain("--console-gateway"); + }); + test("auth login --help 正常退出", async () => { const { stderr, exitCode } = await runCommandHelp(AUTH_ROUTES, ["auth", "login", "--help"]); expect(exitCode, stderr).toBe(0); diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index 076dd13c3..ab77d62df 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -5,6 +5,7 @@ export type E2eRouteExports = Record; export const AUTH_ROUTES: E2eRouteExports = { + auth: "authRoot", "auth login": "authLogin", "auth status": "authStatus", "auth logout": "authLogout", diff --git a/packages/commands/tests/output/catalog-workspace-permission-output.test.ts b/packages/commands/tests/output/catalog-workspace-permission-output.test.ts index c8fe09cd7..da02f76f6 100644 --- a/packages/commands/tests/output/catalog-workspace-permission-output.test.ts +++ b/packages/commands/tests/output/catalog-workspace-permission-output.test.ts @@ -332,17 +332,31 @@ async function invoke(scenario: Scenario, display: Display, flags = scenario.fla }, }, }); + const mixedOpenApi = scenario.command.auth === "openapi"; + const openApiCredential = { + source: "flag" as const, + accessKeyId: "fixture-access-key", + accessKeySecret: "fixture-access-secret", + securityToken: "fixture-security-token", + }; const client = new Client({ identity, - settings, + settings: mixedOpenApi + ? { ...settings, consoleRegion: "cn-beijing", consoleSite: "domestic" } + : settings, baseUrl: "https://fixture.invalid", + ...(mixedOpenApi + ? { openApiCred: openApiCredential, resolveConsoleOpenApiCredential: () => openApiCredential } + : {}), apiCred: { token: "fixture-api-token", source: "flag", baseUrl: "https://fixture.invalid" }, - consoleCred: { - token: "fixture-console-token", - region: "cn-beijing", - site: "domestic", - source: "flag", - }, + consoleCred: mixedOpenApi + ? undefined + : { + token: "fixture-console-token", + region: "cn-beijing", + site: "domestic", + source: "flag", + }, debug: (record) => reporter.output.debug(record), }); let exitCode = 0; diff --git a/packages/commands/tests/output/local-command-output.test.ts b/packages/commands/tests/output/local-command-output.test.ts index 8296be4ed..754b74fca 100644 --- a/packages/commands/tests/output/local-command-output.test.ts +++ b/packages/commands/tests/output/local-command-output.test.ts @@ -227,6 +227,15 @@ async function invoke( settings, baseUrl: "https://fixture.invalid", apiCred: { source: "flag", token: "sk-fixture", baseUrl: "https://fixture.invalid" }, + ...(scenario.command.auth === "openapi" + ? { + openApiCred: { + source: "flag" as const, + accessKeyId: "fixture-ak", + accessKeySecret: "fixture-secret", + }, + } + : {}), }); vi.spyOn(client, "console").mockResolvedValue({ data: { DataV2: { data: { data: { total: 0, mcpServerDetailList: [] } } } }, diff --git a/packages/core/src/auth/aliyun-config.ts b/packages/core/src/auth/aliyun-config.ts new file mode 100644 index 000000000..3ee933835 --- /dev/null +++ b/packages/core/src/auth/aliyun-config.ts @@ -0,0 +1,110 @@ +import { UsageError } from "../errors/base.ts"; +import type { AliyunOAuthProfile } from "./aliyun-types.ts"; + +export const ALIYUN_CLI_CLIENT_ID = "4001958595402383681"; +export const ALIYUN_CLI_SCOPE = "openid /internal/bailian/cli"; +export const ALIYUN_OAUTH_BASE_URL = "https://oauth.aliyun.com"; + +export function normalizeOAuthUrl(value: string, originOnly = false): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new UsageError("Invalid OAuth endpoint. / OAuth 端点无效。"); + } + const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname); + if ( + (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) || + url.username || + url.password || + url.hash || + [...url.searchParams.keys()].some((name) => + [ + "access_token", + "refresh_token", + "client_secret", + "code", + "code_verifier", + "sec_token", + "token", + "authorization", + ].includes(name.toLowerCase()), + ) || + (originOnly && (url.search || (url.pathname !== "/" && url.pathname !== ""))) + ) { + throw new UsageError( + "OAuth endpoints must use HTTPS without credentials or fragments; HTTP is allowed only on loopback. / OAuth 端点必须使用 HTTPS,不能包含凭据或片段;HTTP 仅允许回环地址。", + ); + } + return originOnly ? url.origin : url.toString(); +} + +export function normalizeOpenApiHost(value: string): string { + const host = value.trim(); + const url = normalizeOAuthUrl(`https://${host}`, true); + if (/[\\/?#@\s]/u.test(host)) { + throw new UsageError( + "OpenAPI endpoint must be a hostname with an optional port. / OpenAPI 端点必须是主机名,可包含端口。", + ); + } + return new URL(url).host; +} + +export function parseAliyunOAuthProfile(raw: unknown): AliyunOAuthProfile { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new UsageError("Invalid aliyun_oauth configuration. / aliyun_oauth 配置无效。"); + } + const profile = raw as Record; + const requiredStrings = [ + "client_id", + "scope", + "authorization_url", + "oauth_base_url", + "modelstudio_host", + "console_gateway", + "console_region", + "session_ref", + ] as const; + for (const field of requiredStrings) { + if (typeof profile[field] !== "string" || !profile[field].trim()) { + throw new UsageError(`Invalid aliyun_oauth.${field}. / aliyun_oauth.${field} 无效。`); + } + } + if ( + !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u.test( + profile.session_ref as string, + ) || + typeof profile.console_enabled !== "boolean" || + typeof profile.openapi_enabled !== "boolean" + ) { + throw new UsageError( + "Invalid OAuth session reference or activation state. / OAuth 会话引用或激活状态无效。", + ); + } + const result: AliyunOAuthProfile = { + client_id: (profile.client_id as string).trim(), + scope: (profile.scope as string).trim(), + authorization_url: normalizeOAuthUrl(profile.authorization_url as string), + oauth_base_url: normalizeOAuthUrl(profile.oauth_base_url as string, true), + modelstudio_host: normalizeOpenApiHost(profile.modelstudio_host as string), + console_gateway: normalizeOAuthUrl(profile.console_gateway as string, true), + console_region: (profile.console_region as string).trim(), + session_ref: profile.session_ref as string, + console_enabled: profile.console_enabled, + openapi_enabled: profile.openapi_enabled, + }; + if (profile.bailiancontrol_host !== undefined) { + if (typeof profile.bailiancontrol_host !== "string") + throw new UsageError("Invalid bailiancontrol_host. / bailiancontrol_host 无效。"); + result.bailiancontrol_host = normalizeOpenApiHost(profile.bailiancontrol_host); + } + for (const field of ["access_token_expires_at", "sts_expires_at"] as const) { + const value = profile[field]; + if (value !== undefined) { + if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) + throw new UsageError(`Invalid aliyun_oauth.${field}. / aliyun_oauth.${field} 无效。`); + result[field] = value; + } + } + return result; +} diff --git a/packages/core/src/auth/aliyun-oauth.ts b/packages/core/src/auth/aliyun-oauth.ts new file mode 100644 index 000000000..c2c23a03e --- /dev/null +++ b/packages/core/src/auth/aliyun-oauth.ts @@ -0,0 +1,308 @@ +import { randomBytes, createHash } from "node:crypto"; +import { httpTransport } from "../client/transport.ts"; +import { debugRequest, debugResponse } from "../client/diagnostics.ts"; +import type { HttpDeps } from "../client/http.ts"; +import { trackingHeaders } from "../client/headers.ts"; +import { BailianError, UsageError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; +import type { AliyunOAuthProfile, AliyunOAuthTokens, AliyunOAuthSession } from "./aliyun-types.ts"; + +export interface AliyunOAuthDeps extends Pick { + timeout: number; + now?: () => number; + warning?: HttpDeps["debug"]; + recoveryHint?: string; +} + +export function createOAuthProofKey(): { state: string; verifier: string; challenge: string } { + const verifier = randomBytes(32).toString("base64url"); + return { + state: randomBytes(32).toString("base64url"), + verifier, + challenge: createHash("sha256").update(verifier, "ascii").digest("base64url"), + }; +} + +export function aliyunAuthorizationUrl( + profile: Pick, + redirectUri: string, + proof: ReturnType, +): string { + const url = new URL(profile.authorization_url); + for (const [name, value] of Object.entries({ + response_type: "code", + client_id: profile.client_id, + scope: profile.scope, + redirect_uri: redirectUri, + state: proof.state, + code_challenge: proof.challenge, + code_challenge_method: "S256", + })) + url.searchParams.set(name, value); + return url.toString(); +} + +export function parseAliyunCallback(url: URL, state: string): string { + if (url.searchParams.getAll("state").length !== 1 || url.searchParams.get("state") !== state) { + throw new UsageError("Invalid OAuth state. / OAuth state 无效。"); + } + if (url.searchParams.has("error")) { + throw new BailianError( + "OAuth authorization was denied or failed. / OAuth 授权被拒绝或失败。", + ExitCode.GENERAL, + ); + } + const codes = url.searchParams.getAll("code"); + if (codes.length !== 1 || !codes[0]?.trim()) + throw new UsageError("Missing or duplicate OAuth code. / OAuth code 缺失或重复。"); + return codes[0]; +} + +async function postOAuth( + profile: Pick, + path: string, + deps: AliyunOAuthDeps, + headers: Record, + body?: string, + secrets: string[] = [], +): Promise> { + const endpoint = `${profile.oauth_base_url}${path}`; + debugRequest(deps, "POST", endpoint); + const response = await httpTransport.fetch(endpoint, { + method: "POST", + headers: { ...trackingHeaders(deps.identity), ...headers }, + body, + redirect: "error", + signal: AbortSignal.timeout(deps.timeout * 1000), + }); + debugResponse(deps, response); + const raw = await response.text(); + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new BailianError( + `OAuth response is not JSON (HTTP ${response.status}). / OAuth 响应不是 JSON(HTTP ${response.status})。`, + ExitCode.GENERAL, + ); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) + throw new BailianError("Invalid OAuth response. / OAuth 响应无效。", ExitCode.GENERAL); + const data = parsed as Record; + if (!response.ok || data.error || data.Success === false) { + const errorMessage = + data.error_description ?? data.Message ?? data.message ?? data.error ?? response.statusText; + let message = typeof errorMessage === "string" ? errorMessage : JSON.stringify(errorMessage)!; + for (const secret of secrets.flatMap((value) => [ + value, + encodeURIComponent(value), + new URLSearchParams({ value }).toString().slice(6), + ])) + if (secret) message = message.replaceAll(secret, "[REDACTED]"); + const apiCode = data.error ?? data.Code; + const requestId = data.requestId ?? data.RequestId ?? response.headers.get("x-request-id"); + throw new BailianError(message, ExitCode.GENERAL, undefined, { + api: { + httpStatus: response.status, + apiCode: typeof apiCode === "string" ? apiCode : undefined, + requestId: typeof requestId === "string" ? requestId : undefined, + }, + }); + } + return data; +} + +function tokenResult( + data: Record, + refreshToken: string | undefined, + deps: AliyunOAuthDeps, +): AliyunOAuthTokens { + const accessToken = data.access_token; + const returnedRefreshToken = data.refresh_token; + const rawExpiresIn = data.expires_in; + const expiresIn = + typeof rawExpiresIn === "number" || + (typeof rawExpiresIn === "string" && /^\d+(?:\.\d+)?$/u.test(rawExpiresIn.trim())) + ? Number(rawExpiresIn) + : NaN; + const accessTokenExpiresAt = (deps.now?.() ?? Date.now()) + expiresIn * 1000; + if ( + typeof accessToken !== "string" || + !accessToken.trim() || + !Number.isFinite(expiresIn) || + expiresIn <= 0 || + !Number.isSafeInteger(accessTokenExpiresAt) || + !Number.isFinite(new Date(accessTokenExpiresAt).getTime()) || + (returnedRefreshToken !== undefined && + (typeof returnedRefreshToken !== "string" || !returnedRefreshToken.trim())) || + (data.token_type !== undefined && data.token_type !== "Bearer") + ) + throw new BailianError( + "OAuth response is missing valid token fields. / OAuth 响应缺少有效令牌字段。", + ExitCode.GENERAL, + ); + const effectiveRefreshToken = + typeof returnedRefreshToken === "string" ? returnedRefreshToken : refreshToken; + if (!effectiveRefreshToken) + throw new BailianError( + "Native OAuth login did not return a refresh token. / Native OAuth 登录未返回刷新令牌。", + ExitCode.GENERAL, + ); + return { + accessToken, + refreshToken: effectiveRefreshToken, + accessTokenExpiresAt, + }; +} + +export async function exchangeAliyunCode( + profile: Pick, + code: string, + verifier: string, + redirectUri: string, + deps: AliyunOAuthDeps, +): Promise { + const form = new URLSearchParams({ + grant_type: "authorization_code", + client_id: profile.client_id, + code, + redirect_uri: redirectUri, + code_verifier: verifier, + }); + const data = await postOAuth( + profile, + "/v1/token", + deps, + { "Content-Type": "application/x-www-form-urlencoded" }, + form.toString(), + [code, verifier], + ); + if (typeof data.scope === "string") { + const granted = new Set(data.scope.split(/\s+/u)); + if (profile.scope.split(/\s+/u).some((scope) => !granted.has(scope))) + throw new BailianError( + "OAuth granted scope does not cover the requested scope. / OAuth 授予范围未覆盖请求范围。", + ExitCode.GENERAL, + ); + } + return tokenResult(data, undefined, deps); +} + +export async function refreshAliyunTokens( + profile: Pick, + refreshToken: string, + deps: AliyunOAuthDeps, +): Promise { + const form = new URLSearchParams({ + grant_type: "refresh_token", + client_id: profile.client_id, + refresh_token: refreshToken, + }); + return tokenResult( + await postOAuth( + profile, + "/v1/token", + deps, + { "Content-Type": "application/x-www-form-urlencoded" }, + form.toString(), + [refreshToken], + ), + refreshToken, + deps, + ); +} + +export async function exchangeAliyunSts( + profile: Pick, + accessToken: string, + deps: AliyunOAuthDeps, +): Promise> { + const data = await postOAuth( + profile, + "/v1/exchange", + deps, + { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" }, + undefined, + [accessToken], + ); + const hasPascalCaseFields = [ + "AccessKeyId", + "AccessKeySecret", + "SecurityToken", + "Expiration", + ].some((field) => Object.hasOwn(data, field)); + const { accessKeyId, accessKeySecret, securityToken, expiration } = hasPascalCaseFields + ? { + accessKeyId: data.AccessKeyId, + accessKeySecret: data.AccessKeySecret, + securityToken: data.SecurityToken, + expiration: data.Expiration, + } + : data; + const expiresAt = typeof expiration === "string" ? Date.parse(expiration) : NaN; + if ( + typeof accessKeyId !== "string" || + !accessKeyId.trim() || + typeof accessKeySecret !== "string" || + !accessKeySecret.trim() || + typeof securityToken !== "string" || + !securityToken.trim() || + !Number.isFinite(expiresAt) || + expiresAt <= (deps.now?.() ?? Date.now()) + ) + throw new BailianError( + "OAuth exchange did not return valid STS credentials. / OAuth 置换未返回有效 STS 凭据。", + ExitCode.GENERAL, + ); + return { accessKeyId, accessKeySecret, securityToken, expiresAt }; +} + +export async function revokeAliyunTokens( + profile: Pick, + refreshToken: string, + deps: AliyunOAuthDeps, +): Promise { + const endpoint = `${profile.oauth_base_url}/v1/revoke`; + const form = new URLSearchParams({ client_id: profile.client_id, token: refreshToken }); + debugRequest(deps, "POST", endpoint); + const response = await httpTransport.fetch(endpoint, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + ...trackingHeaders(deps.identity), + }, + body: form.toString(), + redirect: "error", + signal: AbortSignal.timeout(deps.timeout * 1000), + }); + debugResponse(deps, response); + if (!response.ok) { + const raw = await response.text(); + let data: Record = {}; + try { + const parsed: unknown = JSON.parse(raw); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) + data = parsed as Record; + } catch { + /* Non-JSON service errors still retain their HTTP status. */ + } + const description = + data.error_description ?? data.Message ?? data.message ?? data.error ?? response.statusText; + const message = typeof description === "string" ? description : JSON.stringify(description)!; + const apiCode = data.error ?? data.Code; + const requestId = data.requestId ?? data.RequestId ?? response.headers.get("x-request-id"); + throw new BailianError( + message.replaceAll(refreshToken, "[REDACTED]") || `HTTP ${response.status}`, + ExitCode.GENERAL, + undefined, + { + api: { + httpStatus: response.status, + apiCode: typeof apiCode === "string" ? apiCode : undefined, + requestId: typeof requestId === "string" ? requestId : undefined, + }, + }, + ); + } + await response.body?.cancel(); +} diff --git a/packages/core/src/auth/aliyun-types.ts b/packages/core/src/auth/aliyun-types.ts new file mode 100644 index 000000000..b6d2ab512 --- /dev/null +++ b/packages/core/src/auth/aliyun-types.ts @@ -0,0 +1,53 @@ +import type { ConsoleCredential, OpenApiCredential } from "./types.ts"; + +export interface AliyunOAuthProfile { + client_id: string; + scope: string; + authorization_url: string; + oauth_base_url: string; + modelstudio_host: string; + bailiancontrol_host?: string; + console_gateway: string; + console_region: string; + session_ref: string; + console_enabled: boolean; + openapi_enabled: boolean; + access_token_expires_at?: number; + sts_expires_at?: number; +} + +export interface AliyunOAuthTokens { + accessToken: string; + refreshToken: string; + accessTokenExpiresAt: number; +} + +export interface AliyunOAuthSession extends AliyunOAuthTokens { + configurationFingerprint?: string; + refreshPending?: boolean; + sts?: { + accessKeyId: string; + accessKeySecret: string; + securityToken: string; + expiresAt: number; + }; + consoleTokens?: Record; +} + +export interface OpenApiCredentialProvider { + getCredential(purpose?: "openapi" | "console"): Promise; + assertAvailable(purpose?: "openapi" | "console"): void; + resolveHost( + host: string, + credential?: OpenApiCredential, + purpose?: "openapi" | "console", + ): string; + resolveConsoleTarget( + target: Omit, + purpose?: "openapi" | "console", + ): Omit; + getConsoleCredential( + target: Omit, + ): Promise; + saveConsoleCredential(credential: ConsoleCredential): Promise; +} diff --git a/packages/core/src/auth/index.ts b/packages/core/src/auth/index.ts index af7a48860..51ce3893f 100644 --- a/packages/core/src/auth/index.ts +++ b/packages/core/src/auth/index.ts @@ -11,6 +11,36 @@ export { isModelConnectionSourceMismatch, } from "./resolver.ts"; export { makeAuthStore, type AuthStore, type AuthPersistPatch } from "./store.ts"; +export { + createOpenApiCredentialProvider, + consoleCredentialKey, + bindOpenApiConsoleCredentials, +} from "./openapi-provider.ts"; +export { createOAuthSecretStore, type OAuthSecretStore } from "./secure-store.ts"; +export { + ALIYUN_CLI_CLIENT_ID, + ALIYUN_CLI_SCOPE, + ALIYUN_OAUTH_BASE_URL, + normalizeOAuthUrl, + normalizeOpenApiHost, + parseAliyunOAuthProfile, +} from "./aliyun-config.ts"; +export { + createOAuthProofKey, + aliyunAuthorizationUrl, + parseAliyunCallback, + exchangeAliyunCode, + exchangeAliyunSts, + refreshAliyunTokens, + revokeAliyunTokens, + type AliyunOAuthDeps, +} from "./aliyun-oauth.ts"; +export type { + AliyunOAuthProfile, + AliyunOAuthSession, + AliyunOAuthTokens, + OpenApiCredentialProvider, +} from "./aliyun-types.ts"; export type { ApiKeyCredential, ConsoleCredential, @@ -23,5 +53,6 @@ export { generateCLIAccessToken, refreshAccessToken, resolveCLIAccessTokenTarget, + resolveModelStudioHost, validateConsoleAccessToken, } from "./refresh-token.ts"; diff --git a/packages/core/src/auth/openapi-provider.ts b/packages/core/src/auth/openapi-provider.ts new file mode 100644 index 000000000..cb0dd7334 --- /dev/null +++ b/packages/core/src/auth/openapi-provider.ts @@ -0,0 +1,482 @@ +import { dirname, join } from "node:path"; +import { createHash } from "node:crypto"; +import { readConfigFile, mutateConfigFile, type ResolutionSources } from "../config/loader.ts"; +import { getConfigPath } from "../config/paths.ts"; +import { + requirePreConsoleGateway, + resolvePreOpenApiHost, + validatePreAliyunProfile, +} from "../config/control-plane.ts"; +import { CredentialError } from "../errors/credential.ts"; +import { UsageError, BailianError } from "../errors/base.ts"; +import { withFileLock } from "../utils/file-lock.ts"; +import { resolveOpenApi } from "./resolver.ts"; +import { createOAuthSecretStore, type OAuthSecretStore } from "./secure-store.ts"; +import { exchangeAliyunSts, refreshAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; +import type { + AliyunOAuthProfile, + AliyunOAuthSession, + OpenApiCredentialProvider, +} from "./aliyun-types.ts"; +import type { ConsoleCredential, OpenApiCredential } from "./types.ts"; + +type Purpose = "openapi" | "console"; +type ConsoleTarget = Omit; + +export function oauthConfigurationFingerprint( + profile: Omit, +): string { + return createHash("sha256") + .update( + JSON.stringify([ + profile.client_id, + profile.scope, + profile.authorization_url, + profile.oauth_base_url, + profile.modelstudio_host, + profile.bailiancontrol_host ?? null, + profile.console_gateway, + profile.console_region, + ]), + ) + .digest("hex"); +} + +export function assertOAuthConfiguration( + profile: AliyunOAuthProfile, + session: AliyunOAuthSession, +): void { + if (session.configurationFingerprint !== oauthConfigurationFingerprint(profile)) + throw new CredentialError( + "missing-aliyun-session", + "The OAuth endpoints or client configuration changed; sign in again. / OAuth 端点或客户端配置已变更,请重新登录。", + ); +} + +export function oauthSessionLockPath(directory: string, reference: string): string { + return join(directory, "oauth", `${reference}.lock`); +} + +function selectedOAuth( + sources: ResolutionSources, + purpose: Purpose, +): AliyunOAuthProfile | undefined { + if ( + sources.flags.accessKeyId !== undefined || + sources.flags.accessKeySecret !== undefined || + sources.env.BAILIAN_ACCESS_KEY_ID?.trim() || + sources.env.BAILIAN_ACCESS_KEY_SECRET?.trim() + ) + return undefined; + const profile = sources.file.aliyun_oauth; + return profile?.[purpose === "console" ? "console_enabled" : "openapi_enabled"] + ? profile + : undefined; +} + +function hasCompleteCredentialOverride(sources: ResolutionSources): boolean { + if (sources.flags.accessKeyId !== undefined || sources.flags.accessKeySecret !== undefined) + return Boolean(sources.flags.accessKeyId?.trim() && sources.flags.accessKeySecret?.trim()); + return Boolean( + sources.env.BAILIAN_ACCESS_KEY_ID?.trim() && sources.env.BAILIAN_ACCESS_KEY_SECRET?.trim(), + ); +} + +function staticCredential(sources: ResolutionSources): OpenApiCredential { + return resolveOpenApi({ ...sources, file: { ...sources.file, aliyun_oauth: undefined } }); +} + +export function consoleCredentialKey(target: ConsoleTarget): string { + return JSON.stringify([ + target.region, + target.site, + target.switchAgent ?? null, + target.gateway ?? null, + ]); +} + +export function parseOAuthSession(raw: string | undefined): AliyunOAuthSession { + if (!raw) + throw new CredentialError( + "missing-aliyun-session", + "The Aliyun OAuth session is missing. / 阿里云 OAuth 会话缺失。", + ); + let session: AliyunOAuthSession; + try { + session = JSON.parse(raw); + } catch { + throw new CredentialError( + "missing-aliyun-session", + "The Aliyun OAuth session is corrupted. / 阿里云 OAuth 会话已损坏。", + ); + } + if ( + !session || + typeof session.accessToken !== "string" || + typeof session.refreshToken !== "string" || + typeof session.accessTokenExpiresAt !== "number" || + !Number.isFinite(session.accessTokenExpiresAt) + ) + throw new CredentialError( + "missing-aliyun-session", + "Invalid Aliyun OAuth session. / 阿里云 OAuth 会话无效。", + ); + if ( + session.sts && + (typeof session.sts.accessKeyId !== "string" || + !session.sts.accessKeyId || + typeof session.sts.accessKeySecret !== "string" || + !session.sts.accessKeySecret || + typeof session.sts.securityToken !== "string" || + !session.sts.securityToken || + typeof session.sts.expiresAt !== "number" || + !Number.isFinite(session.sts.expiresAt)) + ) + throw new CredentialError( + "missing-aliyun-session", + "Invalid cached STS credentials. / 缓存的 STS 凭据无效。", + ); + if (session.consoleTokens) { + if (typeof session.consoleTokens !== "object" || Array.isArray(session.consoleTokens)) + throw new CredentialError( + "missing-aliyun-session", + "Invalid cached Console credentials. / 缓存的控制台凭据无效。", + ); + for (const cached of Object.values(session.consoleTokens)) + if ( + !cached || + typeof cached.token !== "string" || + !cached.token || + (cached.expiresAt !== undefined && + (typeof cached.expiresAt !== "number" || !Number.isFinite(cached.expiresAt))) + ) + throw new CredentialError( + "missing-aliyun-session", + "Invalid cached Console credentials. / 缓存的控制台凭据无效。", + ); + } + return session; +} + +export function bindOpenApiConsoleCredentials( + provider: OpenApiCredentialProvider, +): OpenApiCredentialProvider { + let identity: string | undefined; + const getCredential = async () => { + const credential = await provider.getCredential(); + const selectedIdentity = + credential.method === "aliyun-oauth" + ? `${credential.sessionRef}:${credential.configurationFingerprint}` + : createHash("sha256") + .update( + JSON.stringify([ + credential.accessKeyId, + credential.accessKeySecret, + credential.securityToken ?? null, + ]), + ) + .digest("hex"); + if (identity !== undefined && identity !== selectedIdentity) + throw new CredentialError( + "changed-openapi-identity", + "OpenAPI credentials changed during this command; rerun it with the intended profile. / 命令执行期间 OpenAPI 凭据已变更,请使用目标配置重新执行。", + ); + identity = selectedIdentity; + return credential; + }; + return { + ...provider, + getCredential, + assertAvailable: () => provider.assertAvailable(), + resolveHost: (host, credential) => provider.resolveHost(host, credential, "openapi"), + resolveConsoleTarget: (target) => provider.resolveConsoleTarget(target, "openapi"), + async getConsoleCredential(target) { + const credential = await getCredential(); + if (credential.method !== "aliyun-oauth") return undefined; + const cached = await provider.getConsoleCredential(target); + return cached && + cached.sessionRef === credential.sessionRef && + cached.configurationFingerprint === credential.configurationFingerprint + ? cached + : undefined; + }, + }; +} + +export function createOpenApiCredentialProvider( + sources: ResolutionSources, + deps: AliyunOAuthDeps, + options: { store?: OAuthSecretStore; directory?: string } = {}, +): OpenApiCredentialProvider { + const boundSources: ResolutionSources = { + ...sources, + flags: { ...sources.flags }, + file: { + ...sources.file, + ...(sources.file.aliyun_oauth ? { aliyun_oauth: { ...sources.file.aliyun_oauth } } : {}), + }, + env: Object.fromEntries( + [ + "BAILIAN_ACCESS_KEY_ID", + "BAILIAN_ACCESS_KEY_SECRET", + "BAILIAN_SECURITY_TOKEN", + "ALIBABA_CLOUD_ACCESS_KEY_ID", + "ALIBABA_CLOUD_ACCESS_KEY_SECRET", + "ALIBABA_CLOUD_SECURITY_TOKEN", + ].map((name) => [name, sources.env[name]]), + ), + }; + const pre = boundSources.preControlPlane; + const configurationPath = boundSources.configPath ?? getConfigPath(pre); + const directory = options.directory ?? dirname(configurationPath); + let store = options.store; + const getStore = () => (store ??= createOAuthSecretStore(directory)); + const sessions = new Map(); + const pending = new Map>(); + const now = () => deps.now?.() ?? Date.now(); + const currentSources = (): ResolutionSources => ({ + ...boundSources, + file: readConfigFile(boundSources.configName, configurationPath), + }); + const assertReference = (profile: AliyunOAuthProfile, purpose: Purpose) => { + if (pre) validatePreAliyunProfile(profile); + const current = currentSources().file.aliyun_oauth; + if ( + current?.session_ref !== profile.session_ref || + !current[purpose === "console" ? "console_enabled" : "openapi_enabled"] || + oauthConfigurationFingerprint(current) !== oauthConfigurationFingerprint(profile) + ) + throw new CredentialError( + "missing-aliyun-session", + "The OAuth login changed or was removed. / OAuth 登录已变更或被移除。", + ); + }; + const credentialFrom = ( + profile: AliyunOAuthProfile, + session: AliyunOAuthSession, + ): OpenApiCredential => ({ + ...session.sts!, + source: "config", + method: "aliyun-oauth", + sessionRef: profile.session_ref, + configurationFingerprint: session.configurationFingerprint, + }); + const save = async (profile: AliyunOAuthProfile, session: AliyunOAuthSession) => { + await getStore().write(profile.session_ref, JSON.stringify(session)); + sessions.set(profile.session_ref, session); + }; + const validateTarget = (profile: AliyunOAuthProfile, target: ConsoleTarget) => { + const gateway = pre ? requirePreConsoleGateway(pre, target) : profile.console_gateway; + if ( + target.region !== profile.console_region || + target.site !== "domestic" || + gateway !== profile.console_gateway || + (target.gateway !== undefined && target.gateway !== profile.console_gateway) + ) + throw new UsageError( + "The Console target differs from the OAuth profile; sign in to a separate profile for that target. / 控制台目标与 OAuth 配置不同,请为该目标登录独立配置。", + ); + }; + + return { + assertAvailable(purpose = "openapi") { + if (purpose === "console" && boundSources.file.aliyun_oauth?.console_enabled) return; + if (!selectedOAuth(boundSources, purpose)) staticCredential(boundSources); + }, + resolveConsoleTarget(target, purpose = "console") { + const profile = currentSources().file.aliyun_oauth; + const active = profile?.[purpose === "console" ? "console_enabled" : "openapi_enabled"]; + if (profile && active) validateTarget(profile, target); + const gateway = pre + ? requirePreConsoleGateway(pre, target) + : profile && active + ? profile.console_gateway + : target.gateway; + return { + region: target.region, + site: target.site, + ...(target.switchAgent !== undefined ? { switchAgent: target.switchAgent } : {}), + ...(gateway !== undefined ? { gateway } : {}), + }; + }, + resolveHost(host, credential, purpose = "openapi") { + const profile = currentSources().file.aliyun_oauth; + if ( + credential?.method === "aliyun-oauth" && + (!profile || + !profile[purpose === "console" ? "console_enabled" : "openapi_enabled"] || + profile.session_ref !== credential.sessionRef || + credential.configurationFingerprint !== oauthConfigurationFingerprint(profile)) + ) + throw new CredentialError( + "missing-aliyun-session", + "The OAuth login changed or was removed. / OAuth 登录已变更或被移除。", + ); + if (pre) return resolvePreOpenApiHost(host); + if (!profile?.[purpose === "console" ? "console_enabled" : "openapi_enabled"]) return host; + if ( + /^modelstudio(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host) || + host === profile.modelstudio_host + ) + return profile.modelstudio_host; + if (/^bailiancontrol(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host)) { + if (!profile.bailiancontrol_host) + throw new UsageError( + "Configure --bailiancontrol-host when signing in before calling BailianControl with this OAuth profile. / 使用此 OAuth 配置调用 BailianControl 前,请在登录时配置 --bailiancontrol-host。", + ); + return profile.bailiancontrol_host; + } + return host; + }, + async getCredential(purpose = "openapi") { + const current = currentSources(); + const profile = selectedOAuth(current, purpose); + if (!profile) return staticCredential(current); + assertReference(profile, purpose); + const cached = sessions.get(profile.session_ref); + if (cached) assertOAuthConfiguration(profile, cached); + if (cached?.sts && cached.sts.expiresAt > now() + 30_000 && !cached.refreshPending) + return credentialFrom(profile, cached); + const existing = pending.get(profile.session_ref); + if (existing) return existing; + const exchange = withFileLock( + oauthSessionLockPath(directory, profile.session_ref), + async () => { + assertReference(profile, purpose); + let session = parseOAuthSession(await getStore().read(profile.session_ref)); + assertOAuthConfiguration(profile, session); + sessions.set(profile.session_ref, session); + if (session.refreshPending) + throw new CredentialError( + "aliyun-refresh-uncertain", + "The previous OAuth refresh did not finish safely; sign in again. / 上次 OAuth 刷新未安全完成,请重新登录。", + ); + if (!session.sts || session.sts.expiresAt <= now() + 30_000) { + if (session.accessTokenExpiresAt <= now() + 30_000) { + if (!session.refreshToken) + throw new CredentialError( + "missing-aliyun-session", + "No OAuth refresh token is available. / 没有可用的 OAuth 刷新令牌。", + ); + session = { ...session, refreshPending: true }; + await save(profile, session); + let tokens; + try { + tokens = await refreshAliyunTokens(profile, session.refreshToken, deps); + } catch (error) { + if (error instanceof BailianError && !error.hint && deps.recoveryHint) + throw new BailianError(error.message, error.exitCode, deps.recoveryHint, { + api: error.api, + cause: error.cause, + }); + throw error; + } + session = { ...session, ...tokens, refreshPending: false, sts: undefined }; + // A rotated RT must be durable before any dependent business request. + await save(profile, session); + } + session = { + ...session, + sts: await exchangeAliyunSts(profile, session.accessToken, deps), + }; + await save(profile, session); + await mutateConfigFile( + (file) => { + if ( + file.aliyun_oauth?.session_ref !== profile.session_ref || + oauthConfigurationFingerprint(file.aliyun_oauth) !== + oauthConfigurationFingerprint(profile) + ) + return undefined; + return { + ...file, + aliyun_oauth: { + ...file.aliyun_oauth, + access_token_expires_at: session.accessTokenExpiresAt, + sts_expires_at: session.sts!.expiresAt, + }, + }; + }, + sources.configName, + { path: configurationPath }, + ); + } + assertReference(profile, purpose); + return credentialFrom(profile, session); + }, + ); + pending.set(profile.session_ref, exchange); + try { + return await exchange; + } finally { + if (pending.get(profile.session_ref) === exchange) pending.delete(profile.session_ref); + } + }, + async getConsoleCredential(target) { + const current = currentSources(); + const profile = current.file.aliyun_oauth; + if (!profile?.console_enabled || hasCompleteCredentialOverride(current)) return undefined; + validateTarget(profile, target); + const scopedTarget = { + region: target.region, + site: target.site, + ...(target.switchAgent !== undefined ? { switchAgent: target.switchAgent } : {}), + gateway: profile.console_gateway, + }; + let session = sessions.get(profile.session_ref); + if (!session) { + session = parseOAuthSession(await getStore().read(profile.session_ref)); + sessions.set(profile.session_ref, session); + } + assertReference(profile, "console"); + assertOAuthConfiguration(profile, session); + const cached = session.consoleTokens?.[consoleCredentialKey(scopedTarget)]; + if (!cached || (cached.expiresAt !== undefined && cached.expiresAt <= now() + 30_000)) + return undefined; + return { + ...scopedTarget, + token: cached.token, + source: "config", + method: "aliyun-oauth", + sessionRef: profile.session_ref, + configurationFingerprint: session.configurationFingerprint, + ...(cached.expiresAt !== undefined ? { expiresAt: cached.expiresAt } : {}), + }; + }, + async saveConsoleCredential(credential) { + const profile = currentSources().file.aliyun_oauth; + if ( + !profile?.console_enabled || + credential.method !== "aliyun-oauth" || + credential.source !== "config" || + credential.sessionRef !== profile.session_ref || + credential.configurationFingerprint !== oauthConfigurationFingerprint(profile) + ) + return; + validateTarget(profile, credential); + await withFileLock(oauthSessionLockPath(directory, profile.session_ref), async () => { + const current = currentSources().file.aliyun_oauth; + if ( + !current || + current.session_ref !== credential.sessionRef || + !current.console_enabled || + credential.configurationFingerprint !== oauthConfigurationFingerprint(current) + ) + return; + const session = parseOAuthSession(await getStore().read(profile.session_ref)); + assertOAuthConfiguration(profile, session); + const key = consoleCredentialKey({ ...credential, gateway: profile.console_gateway }); + await save(profile, { + ...session, + consoleTokens: { + ...session.consoleTokens, + [key]: { + token: credential.token, + ...(credential.expiresAt !== undefined ? { expiresAt: credential.expiresAt } : {}), + }, + }, + }); + }); + }, + }; +} diff --git a/packages/core/src/auth/refresh-token.ts b/packages/core/src/auth/refresh-token.ts index 2f30239bf..f0a9b8401 100644 --- a/packages/core/src/auth/refresh-token.ts +++ b/packages/core/src/auth/refresh-token.ts @@ -1,9 +1,11 @@ import type { HttpDeps } from "../client/http.ts"; import type { Identity, Settings } from "../config/schema.ts"; +import { validatePreConsoleScope } from "../config/control-plane.ts"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; import { callConsoleGateway, type ConsoleGatewayTarget } from "../console/gateway.ts"; -import { readConfigFile, writeConfigFile } from "../config/loader.ts"; +import { readConfigFile, mutateConfigFile } from "../config/loader.ts"; +import { getConfigPath } from "../config/paths.ts"; import { Client } from "../client/client.ts"; import type { OpenApiCredential } from "./types.ts"; @@ -16,11 +18,22 @@ const MODEL_STUDIO_HOSTS = new Map([ ["ap-southeast-1", "modelstudio.ap-southeast-1.aliyuncs.com"], ]); +export function resolveModelStudioHost(region: string): string | undefined { + return MODEL_STUDIO_HOSTS.get(region); +} + /** Console 目标优先;仅在地域缺省时从已知模型域名推导,不猜测未知站点。 */ export function resolveCLIAccessTokenTarget( - settings: Pick, + settings: Pick< + Settings, + "consoleRegion" | "consoleSite" | "consoleSwitchAgent" | "preControlPlane" + >, baseUrl: string, ): Omit { + if (settings.preControlPlane) { + validatePreConsoleScope({ region: settings.consoleRegion, site: settings.consoleSite }); + return { region: "cn-beijing", site: "domestic", switchAgent: settings.consoleSwitchAgent }; + } let region = settings.consoleRegion; if (!region) { let hostname: string | undefined; @@ -60,7 +73,7 @@ export async function validateConsoleAccessToken( target, settings.timeout, { api: "zeldaEasy.cornerstone-portal.cs-console.loginInfo", data: {} }, - diagnostics, + { ...diagnostics, preControlPlane: settings.preControlPlane }, )) as { data?: { success?: boolean } } | null; if (response?.data?.success !== true) { throw new BailianError( @@ -72,27 +85,42 @@ export async function validateConsoleAccessToken( } } -export async function generateCLIAccessToken(opts: { +export type GenerateCLIAccessTokenOptions = { identity: Identity; settings: Settings; debug?: HttpDeps["debug"]; baseUrl: string; - accessKeyId: string; - accessKeySecret: string; - securityToken?: string; -}) { + modelStudioHost?: string; +} & ( + | { client: Client; accessKeyId?: never; accessKeySecret?: never; securityToken?: never } + | { + client?: undefined; + accessKeyId: string; + accessKeySecret: string; + securityToken?: string; + } +); + +export async function generateCLIAccessToken(opts: GenerateCLIAccessTokenOptions) { const { identity, settings, baseUrl, accessKeyId, accessKeySecret, securityToken } = opts; - const client = new Client({ - identity, - settings, - debug: opts.debug, - baseUrl, - openApiCred: { accessKeyId, accessKeySecret, securityToken, source: "flag" }, - }); + const client = + opts.client ?? + new Client({ + identity, + settings, + debug: opts.debug, + baseUrl, + openApiCred: { + accessKeyId: accessKeyId!, + accessKeySecret: accessKeySecret!, + securityToken, + source: "flag", + }, + }); const target = resolveCLIAccessTokenTarget(settings, baseUrl); - const host = MODEL_STUDIO_HOSTS.get(target.region)!; + const host = opts.modelStudioHost ?? resolveModelStudioHost(target.region)!; const response = await client.openApiQueryJson<{ cliAccessToken?: unknown; Success?: boolean }>({ host, @@ -124,11 +152,18 @@ export async function refreshAccessToken(opts: { validateToken?: (token: string) => Promise; /** Already selected by the shared credential chain; legacy callers use the selected config. */ credential?: OpenApiCredential; + modelStudioHost?: string; /** Defaults to persistence only for local config credentials; temporary credentials stay in memory. */ persist?: boolean; }): Promise { const configName = opts.settings.configName; - const config = opts.credential ? undefined : readConfigFile(configName); + const configurationPath = + opts.settings.configPath ?? getConfigPath(opts.settings.preControlPlane); + const config = + !opts.credential || + (opts.credential.source === "config" && opts.credential.method !== "aliyun-oauth") + ? readConfigFile(configName, configurationPath) + : undefined; const accessKeyId = opts.credential?.accessKeyId ?? config?.access_key_id; const accessKeySecret = opts.credential?.accessKeySecret ?? config?.access_key_secret; if (!accessKeyId || !accessKeySecret) return null; @@ -143,6 +178,7 @@ export async function refreshAccessToken(opts: { accessKeyId, accessKeySecret, securityToken: opts.credential ? opts.credential.securityToken : config?.security_token, + modelStudioHost: opts.modelStudioHost, }); const token = resp.cliAccessToken; @@ -156,15 +192,46 @@ export async function refreshAccessToken(opts: { ); } - const persist = opts.persist ?? (!opts.credential || opts.credential.source === "config"); - if (persist) await persistConsoleAccessToken(token, configName); + const persist = + opts.credential?.method !== "aliyun-oauth" && + (opts.persist ?? (!opts.credential || opts.credential.source === "config")); + if (persist) + await persistConsoleAccessToken( + token, + configName, + configurationPath, + config + ? { + token: config.access_token, + accessKeyId: config.access_key_id, + accessKeySecret: config.access_key_secret, + } + : undefined, + ); return token; } /** Called only after a successful Console validation or business request. */ -export async function persistConsoleAccessToken(token: string, configName?: string): Promise { - const existing = readConfigFile(configName) as Record; - existing.access_token = token; - await writeConfigFile(existing, configName); +export async function persistConsoleAccessToken( + token: string, + configName?: string, + path = getConfigPath(), + expected?: { token?: string; accessKeyId?: string; accessKeySecret?: string }, +): Promise { + await mutateConfigFile( + (current) => { + if ( + expected && + (current.access_token !== expected.token || + (expected.accessKeyId !== undefined && current.access_key_id !== expected.accessKeyId) || + (expected.accessKeySecret !== undefined && + current.access_key_secret !== expected.accessKeySecret)) + ) + return undefined; + return { ...current, access_token: token }; + }, + configName, + { path }, + ); } diff --git a/packages/core/src/auth/resolver.ts b/packages/core/src/auth/resolver.ts index caccf138f..c05a3cebb 100644 --- a/packages/core/src/auth/resolver.ts +++ b/packages/core/src/auth/resolver.ts @@ -88,6 +88,11 @@ export function resolveApiKey(s: ResolutionSources): ApiKeyCredential { /** Console-domain credential from sources — access token + 连接目标(flag > file > 默认)。 */ export function resolveConsole(s: ResolutionSources): ConsoleCredential { + if (s.file.aliyun_oauth?.console_enabled) + throw new CredentialError( + "aliyun-oauth-session", + "Console credentials are managed by the Aliyun OAuth session. / 控制台凭据由阿里云 OAuth 会话管理。", + ); const token = s.file.access_token?.trim(); if (!token) { throw new CredentialError("missing-console-token", "No console access token found."); @@ -124,6 +129,12 @@ export function resolveOpenApi(s: ResolutionSources): OpenApiCredential { ); if (envCred) return envCred; + if (s.file.aliyun_oauth?.openapi_enabled) + throw new CredentialError( + "aliyun-oauth-session", + "OpenAPI credentials are managed by the Aliyun OAuth session. / OpenAPI 凭据由阿里云 OAuth 会话管理。", + ); + const configCred = resolveOpenApiPair( "config", s.file.access_key_id, @@ -195,6 +206,7 @@ function openApiPairHint(source: OpenApiCredential["source"], envPrefix: string) /** Full auth snapshot from sources — what would resolve per domain (or undefined). */ export function describeAuthState(s: ResolutionSources): AuthState { const state: AuthState = {}; + if (s.file.aliyun_oauth) state.aliyunOAuth = s.file.aliyun_oauth; try { state.apiKey = resolveApiKey(s); } catch { diff --git a/packages/core/src/auth/secure-store.ts b/packages/core/src/auth/secure-store.ts new file mode 100644 index 000000000..a8bd1d211 --- /dev/null +++ b/packages/core/src/auth/secure-store.ts @@ -0,0 +1,240 @@ +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { constants, type Stats } from "node:fs"; +import { lstat, mkdir, open, rename, unlink } from "node:fs/promises"; +import { join, resolve, win32 } from "node:path"; +import { promisify } from "node:util"; +import { BailianError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; + +export interface OAuthSecretStore { + read(reference: string): Promise; + write(reference: string, value: string): Promise; + remove(reference: string): Promise; +} + +const FAILURES = { + reference: [ + "Invalid OAuth secret reference. / OAuth 凭据文件引用无效。", + "Use a UUID reference. / 请使用 UUID 引用。", + ], + data: [ + "Invalid OAuth session file. / OAuth 会话文件无效。", + "Sign in again to create a new OAuth session. / 请重新登录以创建新的 OAuth 会话。", + ], + file: [ + "OAuth session file access failed. / OAuth 会话文件访问失败。", + "Use a private directory and regular files (700/600 on Unix, private ACLs on Windows). / 请使用私有目录和普通文件(Unix 700/600,Windows 私有 ACL)。", + ], +} as const; + +function failure(reason: keyof typeof FAILURES): BailianError { + const [message, hint] = FAILURES[reason]; + return new BailianError(message, ExitCode.GENERAL, hint); +} + +function normalizeReference(reference: string): string { + if ( + typeof reference !== "string" || + reference.length !== 36 || + !/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(reference) + ) { + throw failure("reference"); + } + return reference.toLowerCase(); +} + +function parseRecord(raw: string): Record { + try { + const data: unknown = JSON.parse(raw); + if (data && typeof data === "object" && !Array.isArray(data)) + return data as Record; + } catch { + throw failure("data"); + } + throw failure("data"); +} + +function readSession(raw: string, reference: string): string { + const record = parseRecord(raw); + if ( + record.reference !== reference || + !record.session || + typeof record.session !== "object" || + Array.isArray(record.session) + ) + throw failure("data"); + return JSON.stringify(record.session); +} + +const isWindows = process.platform === "win32"; +const noFollow = isWindows ? 0 : constants.O_NOFOLLOW; +const execFileAsync = promisify(execFile); + +function isPrivateFile(status: Stats): boolean { + return ( + status.isFile() && + status.nlink === 1 && + (isWindows || ((status.mode & 0o777) === 0o600 && status.uid === process.getuid?.())) + ); +} + +async function assertPrivateWindowsAcl(path: string): Promise { + // Windows chmod cannot remove access granted to other users by an ACL. + const script = [ + "$ErrorActionPreference = 'Stop'", + "$acl = Get-Acl -LiteralPath $env:BAILIAN_OAUTH_ACL_PATH", + "$sidType = [Security.Principal.SecurityIdentifier]", + "$current = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value", + "$trusted = @($current, 'S-1-5-18', 'S-1-5-32-544')", + "if ($trusted -notcontains $acl.GetOwner($sidType).Value) { exit 1 }", + "$currentAllowed = $false", + "foreach ($rule in $acl.GetAccessRules($true, $true, $sidType)) {", + " if ($rule.AccessControlType -ne 'Allow') { continue }", + " if ($trusted -notcontains $rule.IdentityReference.Value) { exit 1 }", + " if ($rule.IdentityReference.Value -eq $current) { $currentAllowed = $true }", + "}", + "if (-not $currentAllowed) { exit 1 }", + ].join("\n"); + await execFileAsync( + win32.join( + process.env.SystemRoot ?? "C:\\Windows", + "System32", + "WindowsPowerShell", + "v1.0", + "powershell.exe", + ), + [ + "-NoProfile", + "-NonInteractive", + "-EncodedCommand", + Buffer.from(script, "utf16le").toString("base64"), + ], + { env: { ...process.env, BAILIAN_OAUTH_ACL_PATH: path }, timeout: 10_000, windowsHide: true }, + ); +} + +export function createOAuthSecretStore(configDirectory: string): OAuthSecretStore { + const rootDirectory = resolve(configDirectory); + const directory = join(rootDirectory, "oauth"); + const filePath = (reference: string) => join(directory, `${reference}.json`); + + async function checkDirectory(create: boolean): Promise { + try { + if (create) await mkdir(rootDirectory, { recursive: true, mode: 0o700 }); + const root = await lstat(rootDirectory); + if ( + !root.isDirectory() || + (!isWindows && ((root.mode & 0o022) !== 0 || root.uid !== process.getuid?.())) + ) + throw failure("file"); + if (isWindows) await assertPrivateWindowsAcl(rootDirectory); + if (create) { + try { + await mkdir(directory, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + } + const status = await lstat(directory); + if ( + !status.isDirectory() || + (!isWindows && ((status.mode & 0o777) !== 0o700 || status.uid !== process.getuid?.())) + ) + throw failure("file"); + if (isWindows) await assertPrivateWindowsAcl(directory); + return true; + } catch (error) { + if (!create && (error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw failure("file"); + } + } + + async function readFile(reference: string): Promise { + if (!(await checkDirectory(false))) return undefined; + const path = filePath(reference); + try { + const original = await lstat(path); + if (!original.isFile()) throw failure("file"); + if (isWindows) await assertPrivateWindowsAcl(path); + const handle = await open(path, constants.O_RDONLY | noFollow); + try { + const status = await handle.stat(); + if (!isPrivateFile(status) || status.ino !== original.ino || status.dev !== original.dev) + throw failure("file"); + return await handle.readFile("utf8"); + } finally { + await handle.close(); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw failure("file"); + } + } + + async function syncDirectory(): Promise { + if (isWindows) return; + const handle = await open(directory, constants.O_RDONLY | noFollow); + try { + await handle.sync(); + } finally { + await handle.close(); + } + } + + async function atomicWrite(reference: string, contents: string): Promise { + await checkDirectory(true); + const temporary = join(directory, `.${reference}.${randomUUID()}.tmp`); + try { + const handle = await open( + temporary, + constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, + 0o600, + ); + try { + try { + if (isWindows) await assertPrivateWindowsAcl(temporary); + else await handle.chmod(0o600); + if (!isPrivateFile(await handle.stat())) throw failure("file"); + await handle.writeFile(contents, "utf8"); + await handle.sync(); + } finally { + await handle.close(); + } + await rename(temporary, filePath(reference)); + await syncDirectory(); + } finally { + await unlink(temporary).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") throw error; + }); + } + } catch { + throw failure("file"); + } + } + + return { + async read(reference) { + const normalized = normalizeReference(reference); + const raw = await readFile(normalized); + return raw === undefined ? undefined : readSession(raw, normalized); + }, + async write(reference, value) { + const normalized = normalizeReference(reference); + const session = parseRecord(value); + const previous = await readFile(normalized); + if (previous !== undefined) readSession(previous, normalized); + await atomicWrite(normalized, JSON.stringify({ reference: normalized, session })); + }, + async remove(reference) { + const normalized = normalizeReference(reference); + if ((await readFile(normalized)) === undefined) return; + try { + await unlink(filePath(normalized)); + await syncDirectory(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw failure("file"); + } + }, + }; +} diff --git a/packages/core/src/auth/store.ts b/packages/core/src/auth/store.ts index 77ba42f70..f1681fa4f 100644 --- a/packages/core/src/auth/store.ts +++ b/packages/core/src/auth/store.ts @@ -1,7 +1,21 @@ import type { ConfigFile } from "../config/schema.ts"; import type { ResolutionSources } from "../config/loader.ts"; -import { readConfigFile, writeConfigFile } from "../config/loader.ts"; +import { readConfigFile, mutateConfigFile } from "../config/loader.ts"; +import { dirname } from "node:path"; +import { randomUUID } from "node:crypto"; +import { withFileLock } from "../utils/file-lock.ts"; +import { createOAuthSecretStore, type OAuthSecretStore } from "./secure-store.ts"; +import { + oauthSessionLockPath, + parseOAuthSession, + oauthConfigurationFingerprint, + assertOAuthConfiguration, +} from "./openapi-provider.ts"; +import { revokeAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; +import type { AliyunOAuthProfile, AliyunOAuthSession } from "./aliyun-types.ts"; +import { CredentialError } from "../errors/credential.ts"; import { getConfigPath } from "../config/paths.ts"; +import { validatePreAliyunProfile } from "../config/control-plane.ts"; import { normalizeModelBaseUrl } from "../config/model-base-url.ts"; import { resolveApiKeyLoginConfigName } from "../config/profile-presets.ts"; import type { AuthState } from "./types.ts"; @@ -10,7 +24,9 @@ import { describeAuthState, resolveModelBaseUrl } from "./resolver.ts"; const LOGOUT_KEYS = { console: ["access_token"], openapi: ["access_key_id", "access_key_secret", "security_token"], + aliyun: [], all: [ + "aliyun_oauth", "api_key", "base_url", "access_token", @@ -57,32 +73,53 @@ export interface AuthStore { openapi: boolean; baseUrl?: string; apiKeyCapabilities?: string[]; + aliyunOAuth?: boolean; }; /** model 域 baseUrl 链(flag > env > config file > fallback)。 */ resolveBaseUrl(fallback?: string): string; /** 登录落盘:合并写入,undefined 键忽略;显式 --config 成功后同时激活目标 Profile。 */ login(patch: AuthPersistPatch): Promise; + loginAliyun( + profile: Omit, + session: AliyunOAuthSession, + ): Promise; /** 清凭证:console/openapi 只删对应域;all 清全部登录凭证和 model baseUrl。返回是否有变更。 */ - logout(scope: "console" | "openapi" | "all"): Promise; + logout(scope: "console" | "openapi" | "aliyun" | "all"): Promise; /** 实际写入的 config.json 路径(不受命名配置影响,一直是同一个文件)。 */ path: string; } -export function makeAuthStore(sources: ResolutionSources): AuthStore { +export function makeAuthStore( + sources: ResolutionSources, + oauthDeps?: AliyunOAuthDeps, + options: { store?: OAuthSecretStore; directory?: string } = {}, +): AuthStore { const configName = sources.configName; const activateAfterLogin = sources.flags.config !== undefined; + const pre = sources.preControlPlane; + const configurationPath = sources.configPath ?? getConfigPath(pre); + const directory = options.directory ?? dirname(configurationPath); + const readBoundConfig = (name = configName) => readConfigFile(name, configurationPath); + let secretStore = options.store; + const getSecretStore = () => (secretStore ??= createOAuthSecretStore(directory)); return { // Read the config block live (not the startup `sources.file` snapshot) so // long-lived processes like `config ui` reflect a fresh login without a // restart. For one-shot commands this reads the same content the snapshot // held, so behavior is unchanged. - describe: () => describeAuthState({ ...sources, file: readConfigFile(configName) }), + describe: () => describeAuthState({ ...sources, file: readBoundConfig() }), stored() { - const file = readConfigFile(configName); + const file = readBoundConfig(); return { apiKey: !!file.api_key, - console: !!file.access_token, - openapi: !!(file.access_key_id || file.access_key_secret || file.security_token), + console: !!(file.access_token || file.aliyun_oauth?.console_enabled), + openapi: !!( + file.access_key_id || + file.access_key_secret || + file.security_token || + file.aliyun_oauth?.openapi_enabled + ), + ...(file.aliyun_oauth ? { aliyunOAuth: true } : {}), baseUrl: file.base_url, apiKeyCapabilities: file.api_key_capabilities, }; @@ -93,31 +130,152 @@ export function makeAuthStore(sources: ResolutionSources): AuthStore { ? resolveApiKeyLoginConfigName(patch.api_key, configName, activateAfterLogin) : configName; const shouldActivate = activateAfterLogin || targetConfigName !== configName; - const existing = readConfigFile(targetConfigName) as Record; - - for (const [key, value] of Object.entries(patch)) { - if (value !== undefined) { - if (key === "api_key_capabilities" && Array.isArray(value)) { - const storedCapabilities = Array.isArray(existing[key]) ? existing[key] : []; - existing[key] = [...new Set([...storedCapabilities, ...value])]; - } else { - existing[key] = key === "base_url" ? normalizeModelBaseUrl(String(value)) : value; + await mutateConfigFile( + (current) => { + const existing = { ...current } as Record; + for (const [key, value] of Object.entries(patch)) { + if (value !== undefined) { + if (key === "api_key_capabilities" && Array.isArray(value)) { + const storedCapabilities = Array.isArray(existing[key]) ? existing[key] : []; + existing[key] = [...new Set([...storedCapabilities, ...value])]; + } else + existing[key] = key === "base_url" ? normalizeModelBaseUrl(String(value)) : value; + } + } + if (current.aliyun_oauth) { + existing.aliyun_oauth = { + ...current.aliyun_oauth, + ...(patch.access_token !== undefined ? { console_enabled: false } : {}), + ...(patch.access_key_id !== undefined || patch.access_key_secret !== undefined + ? { openapi_enabled: false } + : {}), + }; } + return existing as ConfigFile; + }, + targetConfigName, + { activate: shouldActivate, path: configurationPath }, + ); + }, + async loginAliyun(profile, session) { + if (pre) validatePreAliyunProfile(profile); + const reference = randomUUID(); + let previous: AliyunOAuthProfile | undefined; + const metadata: AliyunOAuthProfile = { + ...profile, + session_ref: reference, + console_enabled: true, + openapi_enabled: true, + access_token_expires_at: session.accessTokenExpiresAt, + sts_expires_at: session.sts?.expiresAt, + }; + await withFileLock(oauthSessionLockPath(directory, reference), async () => { + await getSecretStore().write( + reference, + JSON.stringify({ + ...session, + configurationFingerprint: oauthConfigurationFingerprint(metadata), + }), + ); + try { + await mutateConfigFile( + (current) => { + previous = current.aliyun_oauth; + return { + ...current, + aliyun_oauth: metadata, + console_region: profile.console_region, + console_site: "domestic", + console_switch_agent: undefined, + }; + }, + configName, + { activate: activateAfterLogin, path: configurationPath }, + ); + } catch (error) { + await getSecretStore() + .remove(reference) + .catch(() => {}); + throw error; + } + }); + if (previous) { + const referenceToRemove = previous.session_ref; + try { + await withFileLock(oauthSessionLockPath(directory, referenceToRemove), () => + getSecretStore().remove(referenceToRemove), + ); + } catch { + oauthDeps?.warning?.({ + message: { + "en-US": "Signed in, but the previous OAuth session file could not be removed.", + "zh-CN": "登录成功,但未能清理之前的 OAuth 会话文件。", + }, + }); } } - await writeConfigFile(existing, targetConfigName, { activate: shouldActivate }); }, async logout(scope) { - const existing = readConfigFile(configName) as Record; - const keys = LOGOUT_KEYS[scope]; - const had = keys.some((key) => existing[key] !== undefined); - if (!had) return false; - for (const key of keys) delete existing[key]; - await writeConfigFile(existing, configName); - return true; + const profile = readBoundConfig().aliyun_oauth; + const clearConfig = async (reference?: string, removeOAuth = false) => { + let cleared = false; + await mutateConfigFile( + (current) => { + if (reference && current.aliyun_oauth?.session_ref !== reference) return undefined; + const existing = { ...current }; + const keys = LOGOUT_KEYS[scope]; + cleared = keys.some((key) => existing[key] !== undefined) || Boolean(reference); + if (!cleared) return undefined; + for (const key of keys) delete existing[key]; + if (removeOAuth) delete existing.aliyun_oauth; + else if (existing.aliyun_oauth) + existing.aliyun_oauth = { + ...existing.aliyun_oauth, + ...(scope === "console" ? { console_enabled: false } : {}), + ...(scope === "openapi" ? { openapi_enabled: false } : {}), + }; + return existing; + }, + configName, + { path: configurationPath }, + ); + return cleared; + }; + if (!profile) return clearConfig(); + return withFileLock(oauthSessionLockPath(directory, profile.session_ref), async () => { + const current = readBoundConfig().aliyun_oauth; + if (current?.session_ref !== profile.session_ref) return false; + if (pre) validatePreAliyunProfile(current); + const removeOAuth = scope === "all" || scope === "aliyun"; + const raw = await getSecretStore().read(profile.session_ref); + if (removeOAuth) { + if (raw) { + const session = parseOAuthSession(raw); + assertOAuthConfiguration(profile, session); + if (session.refreshToken) { + if (!oauthDeps) + throw new CredentialError( + "missing-aliyun-session", + "OAuth logout requires OAuth transport dependencies. / OAuth 退出需要 OAuth 传输配置。", + ); + await revokeAliyunTokens(profile, session.refreshToken, oauthDeps); + } + } + await getSecretStore().remove(profile.session_ref); + return clearConfig(profile.session_ref, true); + } + if (scope === "console" && raw) { + const session = parseOAuthSession(raw); + await getSecretStore().write( + profile.session_ref, + JSON.stringify({ ...session, consoleTokens: {} }), + ); + } + return clearConfig(profile.session_ref); + }); }, get path() { - return sources.configPath ?? getConfigPath(); + return configurationPath; }, }; } diff --git a/packages/core/src/auth/types.ts b/packages/core/src/auth/types.ts index 78ecec533..dfb826b1b 100644 --- a/packages/core/src/auth/types.ts +++ b/packages/core/src/auth/types.ts @@ -1,3 +1,5 @@ +import type { AliyunOAuthProfile } from "./aliyun-types.ts"; + /** Where a resolved credential came from (shown by `bl auth status`). */ export type CredentialSource = "flag" | "env" | "config"; @@ -21,6 +23,11 @@ export interface ApiKeyCredential { /** Credential for the **console domain** (Bailian console gateway). An access token + region/site. */ export interface ConsoleCredential { token: string; + gateway?: string; + expiresAt?: number; + method?: "aliyun-oauth"; + sessionRef?: string; + configurationFingerprint?: string; region: string; site: "domestic" | "international"; switchAgent?: number; @@ -29,6 +36,10 @@ export interface ConsoleCredential { /** Credential for Alibaba Cloud OpenAPI calls signed with AK/SK. */ export interface OpenApiCredential { + method?: "aliyun-oauth"; + sessionRef?: string; + configurationFingerprint?: string; + expiresAt?: number; accessKeyId: string; accessKeySecret: string; securityToken?: string; @@ -37,6 +48,7 @@ export interface OpenApiCredential { /** Full auth snapshot for display (`bl auth status`) — what would resolve per domain. */ export interface AuthState { + aliyunOAuth?: AliyunOAuthProfile; apiKey?: ApiKeyCredential; console?: ConsoleCredential; openapi?: OpenApiCredential; diff --git a/packages/core/src/client/bailian-control.ts b/packages/core/src/client/bailian-control.ts index 85e925746..64faff781 100644 --- a/packages/core/src/client/bailian-control.ts +++ b/packages/core/src/client/bailian-control.ts @@ -17,18 +17,24 @@ function bailianControlHost(regionId: string): string { } /** Shared inputs for every BailianControl OpenAPI call (AK/SK passed explicitly). */ -export interface BailianControlAuth { +export type BailianControlAuth = { identity: Identity; settings: Settings; baseUrl: string; regionId: string; - accessKeyId: string; - accessKeySecret: string; - securityToken?: string; debug?: HttpDeps["debug"]; -} +} & ( + | { client: Client; accessKeyId?: never; accessKeySecret?: never; securityToken?: never } + | { + client?: undefined; + accessKeyId: string; + accessKeySecret: string; + securityToken?: string; + } +); function bailianControlClient(auth: BailianControlAuth): Client { + if (auth.client) return auth.client; return new Client({ identity: auth.identity, settings: auth.settings, diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index 8e4ca1538..5095fb098 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -1,8 +1,11 @@ import { httpTransport } from "./transport.ts"; import type { Identity, Settings } from "../config/schema.ts"; +import { resolvePreOpenApiHost, validatePreConsoleScope } from "../config/control-plane.ts"; import type { ApiKeyCredential, ConsoleCredential, OpenApiCredential } from "../auth/types.ts"; +import type { OpenApiCredentialProvider } from "../auth/aliyun-types.ts"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; +import { CredentialError } from "../errors/credential.ts"; import { request, requestJson, type HttpDeps, type RequestOpts } from "./http.ts"; import { buildAcsCanonicalQuery, signAcsRequest, type AcsQueryParams } from "./acs.ts"; import { imageFileToDataUri, isLocalFile, resolveFileUrl } from "../files/upload.ts"; @@ -30,7 +33,8 @@ export interface ClientDeps { apiCred?: ApiKeyCredential; consoleCred?: ConsoleCredential; /** Lazily resolve AK/SK only when the Console token is missing or expired. */ - resolveConsoleOpenApiCredential?: () => OpenApiCredential; + resolveConsoleOpenApiCredential?: () => OpenApiCredential | Promise; + openApiProvider?: OpenApiCredentialProvider; /** Optional host-provided recovery text; core does not construct CLI instructions. */ consoleRecoveryHint?: string; openApiCred?: OpenApiCredential; @@ -62,6 +66,7 @@ export interface ClientOpenApiJsonOpts { } export interface OpenApiResponse { + RequestId?: string; Success?: boolean; Code?: string; Message?: string; @@ -93,7 +98,8 @@ export class Client { return this.deps.apiCred; } - private requireOpenApi(): OpenApiCredential { + private async requireOpenApi(): Promise { + if (this.deps.openApiProvider) return this.deps.openApiProvider.getCredential(); if (!this.deps.openApiCred) { throw new BailianError( "This command needs Alibaba Cloud OpenAPI AK/SK credentials.", @@ -261,15 +267,39 @@ export class Client { return this.consoleSession.request(api, data); } + resolveOpenApiHost(host: string, credential?: OpenApiCredential): string { + const { settings, openApiProvider } = this.deps; + if (settings.preControlPlane) { + validatePreConsoleScope({ region: settings.consoleRegion, site: settings.consoleSite }); + const expected = resolvePreOpenApiHost(host); + const resolved = openApiProvider?.resolveHost(host, credential) ?? expected; + if (resolvePreOpenApiHost(resolved) !== expected) { + throw new CredentialError( + "changed-openapi-identity", + "The OpenAPI endpoint does not match the pre-release route. / OpenAPI 端点与预发路由不匹配。", + ); + } + return expected; + } + return openApiProvider?.resolveHost(host, credential) ?? host; + } + openApiQueryJson(opts: ClientOpenApiQueryOpts): Promise { return this.openApiJson(opts); } async openApiJson(opts: ClientOpenApiJsonOpts): Promise { - const cred = this.requireOpenApi(); + const expectedHost = this.resolveOpenApiHost(opts.host); + const cred = await this.requireOpenApi(); + const host = this.resolveOpenApiHost(opts.host, cred); + if (host !== expectedHost) + throw new CredentialError( + "changed-openapi-identity", + "The OpenAPI endpoint changed before signing. / 签名前 OpenAPI 端点已变更。", + ); const bodyStr = opts.body === undefined ? "" : JSON.stringify(opts.body); const queryString = opts.queryParams ? buildAcsCanonicalQuery(opts.queryParams) : ""; - const endpoint = `https://${opts.host}${opts.path}${queryString ? `?${queryString}` : ""}`; + const endpoint = `https://${host}${opts.path}${queryString ? `?${queryString}` : ""}`; const headers = signAcsRequest({ accessKeyId: cred.accessKeyId, accessKeySecret: cred.accessKeySecret, @@ -277,7 +307,7 @@ export class Client { action: opts.action, version: opts.version, body: bodyStr, - host: opts.host, + host, pathname: opts.path, method: opts.method, queryString, @@ -290,25 +320,33 @@ export class Client { method: opts.method, headers: { ...headers, ...trackingHeaders(this.deps.identity) }, body: bodyStr || undefined, + redirect: "error", signal: AbortSignal.timeout(timeoutMs), }); const rawText = await res.text(); debugResponse(this.http, res); + const redact = (value: string) => + [cred.accessKeySecret, cred.securityToken].reduce( + (message, secret) => (secret ? message.replaceAll(secret, "[REDACTED]") : message), + value, + ); let data: T; try { data = JSON.parse(rawText) as T; } catch { throw new BailianError( - `${res.status} ${res.statusText} - ${rawText.slice(0, 500)}`, + redact(`${res.status} ${res.statusText} - ${rawText.slice(0, 500)}`), ExitCode.GENERAL, ); } if (!res.ok || data.Success === false) { throw new BailianError( - `${data.Code || res.status} - ${data.Message || res.statusText}`, + redact(`${data.Code || res.status} - ${data.Message || res.statusText}`), ExitCode.GENERAL, + undefined, + { api: { httpStatus: res.status, apiCode: data.Code, requestId: data.RequestId } }, ); } diff --git a/packages/core/src/client/console-session.ts b/packages/core/src/client/console-session.ts index 10d525b56..3bf5c87d6 100644 --- a/packages/core/src/client/console-session.ts +++ b/packages/core/src/client/console-session.ts @@ -1,9 +1,12 @@ import type { Identity, Settings } from "../config/schema.ts"; import type { ConsoleCredential, OpenApiCredential } from "../auth/types.ts"; +import type { OpenApiCredentialProvider } from "../auth/aliyun-types.ts"; import type { HttpDeps } from "./http.ts"; import { BailianError } from "../errors/base.ts"; import { CredentialError } from "../errors/credential.ts"; import { ExitCode } from "../errors/codes.ts"; +import { getConfigPath } from "../config/paths.ts"; +import { requirePreConsoleGateway } from "../config/control-plane.ts"; import { callConsoleGateway } from "../console/gateway.ts"; import { persistConsoleAccessToken, @@ -17,7 +20,8 @@ interface ConsoleSessionOptions { baseUrl: string; debug?: HttpDeps["debug"]; consoleCred?: ConsoleCredential; - resolveConsoleOpenApiCredential?: () => OpenApiCredential; + resolveConsoleOpenApiCredential?: () => OpenApiCredential | Promise; + openApiProvider?: OpenApiCredentialProvider; consoleRecoveryHint?: string; } @@ -37,8 +41,11 @@ interface ConsoleTokenRefresh { export class ConsoleSession { private consoleTokenPersisted: boolean; private consoleRefresh?: ConsoleTokenRefresh; + private readonly configurationPath: string; constructor(private readonly deps: ConsoleSessionOptions) { + this.configurationPath = + deps.settings.configPath ?? getConfigPath(deps.settings.preControlPlane); this.consoleTokenPersisted = deps.consoleCred?.source === "config"; } @@ -46,7 +53,11 @@ export class ConsoleSession { withSwitchAgent(switchAgent: number): ConsoleSession { const session = new ConsoleSession({ ...this.deps, - settings: { ...this.deps.settings, consoleSwitchAgent: switchAgent }, + settings: { + ...this.deps.settings, + configPath: this.configurationPath, + consoleSwitchAgent: switchAgent, + }, consoleCred: this.deps.consoleCred ? { ...this.deps.consoleCred, switchAgent } : undefined, }); session.consoleTokenPersisted = this.consoleTokenPersisted; @@ -54,19 +65,47 @@ export class ConsoleSession { } async request(api: string, data: Record): Promise { + const { settings, consoleCred } = this.deps; + const pre = settings.preControlPlane; + if (pre && (consoleCred || this.deps.resolveConsoleOpenApiCredential)) { + requirePreConsoleGateway(pre, { + region: consoleCred?.region ?? settings.consoleRegion, + site: consoleCred?.site ?? settings.consoleSite, + }); + } return this.dispatch( (credential) => callConsoleGateway( credential, this.deps.settings.timeout, { api, data }, - { debug: this.deps.debug, recoveryHint: this.deps.consoleRecoveryHint }, + { + debug: this.deps.debug, + recoveryHint: this.deps.consoleRecoveryHint, + preControlPlane: pre, + }, ) as Promise, ); } /** Shared credential lifecycle: lazy issuance and expired-session refresh. */ private async dispatch(invoke: (credential: ConsoleCredential) => Promise): Promise { + if ( + this.deps.openApiProvider && + (!this.deps.consoleCred || this.deps.consoleCred.method === "aliyun-oauth") + ) { + const target = + this.deps.consoleCred ?? resolveCLIAccessTokenTarget(this.deps.settings, this.deps.baseUrl); + const cached = await this.deps.openApiProvider.getConsoleCredential(target); + if ( + !cached || + cached.token !== this.deps.consoleCred?.token || + cached.gateway !== this.deps.consoleCred?.gateway || + cached.sessionRef !== this.deps.consoleCred?.sessionRef || + cached.configurationFingerprint !== this.deps.consoleCred?.configurationFingerprint + ) + this.deps.consoleCred = cached; + } const credential = this.deps.consoleCred; if (!credential) { const failure = new BailianError("This command needs a console access token.", ExitCode.AUTH); @@ -107,8 +146,17 @@ export class ConsoleSession { const result = await invoke(exchange.credential); refresh.commit ??= (async () => { if (this.deps.consoleCred !== previous) return; - if (exchange.persist) - await persistConsoleAccessToken(exchange.credential.token, this.deps.settings.configName); + if (exchange.persist) { + if (exchange.credential.method === "aliyun-oauth") + await this.deps.openApiProvider?.saveConsoleCredential(exchange.credential); + else + await persistConsoleAccessToken( + exchange.credential.token, + this.deps.settings.configName, + this.configurationPath, + previous ? { token: previous.token } : undefined, + ); + } this.consoleTokenPersisted = exchange.persist; this.deps.consoleCred = exchange.credential; })(); @@ -123,16 +171,27 @@ export class ConsoleSession { private async exchangeConsoleToken( previous?: ConsoleCredential, ): Promise { - const credential = this.deps.resolveConsoleOpenApiCredential?.(); - const target = previous ?? resolveCLIAccessTokenTarget(this.deps.settings, this.deps.baseUrl); + const credential = await this.deps.resolveConsoleOpenApiCredential?.(); + const unresolvedTarget = previous + ? { + region: previous.region, + site: previous.site, + ...(previous.switchAgent !== undefined ? { switchAgent: previous.switchAgent } : {}), + ...(previous.gateway !== undefined ? { gateway: previous.gateway } : {}), + } + : resolveCLIAccessTokenTarget(this.deps.settings, this.deps.baseUrl); + const target = + this.deps.openApiProvider?.resolveConsoleTarget(unresolvedTarget) ?? unresolvedTarget; const persist = - this.consoleTokenPersisted && - previous?.source === "config" && - (!credential || credential.source === "config"); + credential?.method === "aliyun-oauth" || + (this.consoleTokenPersisted && + previous?.source === "config" && + (!credential || credential.source === "config")); const token = await refreshAccessToken({ identity: this.deps.identity, settings: { ...this.deps.settings, + configPath: this.configurationPath, consoleRegion: target.region, consoleSite: target.site, consoleSwitchAgent: target.switchAgent, @@ -140,6 +199,11 @@ export class ConsoleSession { debug: this.deps.debug, baseUrl: this.deps.baseUrl, credential, + modelStudioHost: this.deps.openApiProvider?.resolveHost( + `modelstudio.${target.region}.aliyuncs.com`, + credential, + "console", + ), persist: false, // Each waiting caller validates by executing its own business request. validateToken: async () => {}, @@ -150,6 +214,13 @@ export class ConsoleSession { ...target, token, source: credential?.source ?? previous?.source ?? "config", + ...(credential?.method === "aliyun-oauth" + ? { + method: "aliyun-oauth" as const, + sessionRef: credential.sessionRef, + configurationFingerprint: credential.configurationFingerprint, + } + : {}), }, persist, }; diff --git a/packages/core/src/config/control-plane.ts b/packages/core/src/config/control-plane.ts new file mode 100644 index 000000000..0f4523427 --- /dev/null +++ b/packages/core/src/config/control-plane.ts @@ -0,0 +1,105 @@ +import { normalizeOAuthUrl } from "../auth/aliyun-config.ts"; +import type { AliyunOAuthProfile } from "../auth/aliyun-types.ts"; +import { UsageError } from "../errors/base.ts"; + +export const PRE_ALIYUN_AUTHORIZATION_URL = "https://signin.aliyun.com/oauth2/v1/auth"; +export const PRE_ALIYUN_OAUTH_BASE_URL = "https://pre-oauth-cn-shanghai.aliyun.com"; +export const PRE_MODEL_STUDIO_HOST = "modelstudio-pre.aliyuncs.com"; +export const PRE_BAILIAN_CONTROL_HOST = "bailiancontrol-pre.aliyuncs.com"; + +const PRE_CONSOLE_ORIGIN = "https://pre-bailian.console.aliyun.com"; +const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; + +export interface PreControlPlane { + consoleOrigin?: string; + consoleGateway?: string; +} + +export function resolvePreControlPlane(env: NodeJS.ProcessEnv): PreControlPlane | undefined { + const value = env.BAILIAN_PRE?.trim().toLowerCase(); + if (!value || value === "0" || value === "false") return undefined; + if (value !== "1" && value !== "true") { + throw new UsageError( + "Use 1, true, 0 or false for BAILIAN_PRE. / BAILIAN_PRE 仅接受 1、true、0 或 false。", + ); + } + const consoleOrigin = env.BAILIAN_PRE_CONSOLE_ORIGIN?.trim(); + const consoleGateway = env.BAILIAN_PRE_CONSOLE_GATEWAY?.trim(); + const settings = { + ...(consoleOrigin ? { consoleOrigin: normalizeOAuthUrl(consoleOrigin, true) } : {}), + ...(consoleGateway ? { consoleGateway: normalizeOAuthUrl(consoleGateway, true) } : {}), + }; + if (settings.consoleOrigin) requirePreConsoleOrigin(settings, {}); + if (settings.consoleGateway) requirePreConsoleGateway(settings, {}); + return settings; +} + +export function validatePreConsoleScope(target: { region?: string; site?: string }): void { + if ( + (target.region !== undefined && target.region !== "cn-beijing") || + (target.site !== undefined && target.site !== "domestic") + ) { + throw new UsageError( + "The pre-release control plane supports only the domestic cn-beijing site. / 预发控制面当前仅支持国内站 cn-beijing。", + ); + } +} + +export function requirePreConsoleOrigin( + pre: PreControlPlane, + target: { region?: string; site?: string }, +): string { + validatePreConsoleScope(target); + if (pre.consoleOrigin !== PRE_CONSOLE_ORIGIN) { + throw new UsageError( + "Set BAILIAN_PRE_CONSOLE_ORIGIN to the confirmed domestic pre-release Console login origin. / 请将 BAILIAN_PRE_CONSOLE_ORIGIN 设为已确认的国内预发控制台登录源站。", + ); + } + return pre.consoleOrigin; +} + +export function requirePreConsoleGateway( + pre: PreControlPlane, + target: { region?: string; site?: string }, +): string { + validatePreConsoleScope(target); + if (pre.consoleGateway !== PRE_CONSOLE_GATEWAY) { + throw new UsageError( + "Set BAILIAN_PRE_CONSOLE_GATEWAY to the confirmed domestic pre-release CLI gateway. / 请将 BAILIAN_PRE_CONSOLE_GATEWAY 设为已确认的国内预发 CLI 网关。", + ); + } + return pre.consoleGateway; +} + +export function resolvePreOpenApiHost(host: string): string { + switch (host) { + case "modelstudio.aliyuncs.com": + case "modelstudio.cn-beijing.aliyuncs.com": + case PRE_MODEL_STUDIO_HOST: + return PRE_MODEL_STUDIO_HOST; + case "bailiancontrol.aliyuncs.com": + case "bailiancontrol.cn-beijing.aliyuncs.com": + case PRE_BAILIAN_CONTROL_HOST: + return PRE_BAILIAN_CONTROL_HOST; + default: + throw new UsageError( + "This OpenAPI endpoint is not available in the pre-release control plane. / 此 OpenAPI 端点在预发控制面不可用。", + ); + } +} + +export function validatePreAliyunProfile(profile: Omit): void { + validatePreConsoleScope({ region: profile.console_region }); + if ( + profile.authorization_url !== PRE_ALIYUN_AUTHORIZATION_URL || + profile.oauth_base_url !== PRE_ALIYUN_OAUTH_BASE_URL || + profile.modelstudio_host !== PRE_MODEL_STUDIO_HOST || + (profile.bailiancontrol_host !== undefined && + profile.bailiancontrol_host !== PRE_BAILIAN_CONTROL_HOST) || + profile.console_gateway !== PRE_CONSOLE_GATEWAY + ) { + throw new UsageError( + "Aliyun OAuth profile endpoints do not match the pre-release control plane. / 阿里云 OAuth 配置端点与预发控制面不匹配。", + ); + } +} diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.ts index 3b90bbcda..8432f9e43 100644 --- a/packages/core/src/config/index.ts +++ b/packages/core/src/config/index.ts @@ -11,7 +11,12 @@ export { normalizeApiKeyCapabilities, parseConfigFile, } from "./schema.ts"; -export { normalizeConfigName, readConfigFile, writeConfigFile } from "./loader.ts"; +export { + normalizeConfigName, + readConfigFile, + writeConfigFile, + mutateConfigFile, +} from "./loader.ts"; export { activateConfigProfile, validateConfigProfileActivation, @@ -37,3 +42,15 @@ export { } from "./profile-presets.ts"; export { normalizeModelBaseUrl } from "./model-base-url.ts"; export { validateTimeout } from "./validation.ts"; +export { + PRE_ALIYUN_AUTHORIZATION_URL, + PRE_ALIYUN_OAUTH_BASE_URL, + PRE_MODEL_STUDIO_HOST, + PRE_BAILIAN_CONTROL_HOST, + requirePreConsoleGateway, + requirePreConsoleOrigin, + resolvePreControlPlane, + resolvePreOpenApiHost, + validatePreConsoleScope, + type PreControlPlane, +} from "./control-plane.ts"; diff --git a/packages/core/src/config/loader.ts b/packages/core/src/config/loader.ts index 85216d5a3..5ed9b5357 100644 --- a/packages/core/src/config/loader.ts +++ b/packages/core/src/config/loader.ts @@ -1,7 +1,20 @@ import type { OutputDiagnostic } from "../types/output.ts"; -import { readFileSync, writeFileSync, renameSync, existsSync } from "fs"; +import { + readFileSync, + writeFileSync, + renameSync, + existsSync, + openSync, + closeSync, + fsyncSync, + unlinkSync, +} from "fs"; +import { randomUUID } from "node:crypto"; +import { dirname } from "node:path"; +import { withFileLock } from "../utils/file-lock.ts"; import { CONFIG_FILE_KEYS, parseConfigFile, type ConfigFile, type Settings } from "./schema.ts"; -import { ensureConfigDir, getConfigPath } from "./paths.ts"; +import { ensureConfigDir, getConfigPath, isPreConfigPath } from "./paths.ts"; +import type { PreControlPlane } from "./control-plane.ts"; import { detectOutputFormat } from "../output/formatter.ts"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; @@ -10,6 +23,15 @@ import { validateTimeout } from "./validation.ts"; const CONFIG_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/; const ACTIVE_CONFIG_KEY = "active_config"; +const CONTROL_ENVIRONMENT_KEY = "control_environment"; + +function isReservedConfigKey(key: string): boolean { + return ( + key === ACTIVE_CONFIG_KEY || + key === CONTROL_ENVIRONMENT_KEY || + (CONFIG_FILE_KEYS as readonly string[]).includes(key) + ); +} function isConfigBlock(value: unknown): value is Record { return Boolean(value && typeof value === "object" && !Array.isArray(value)); @@ -29,7 +51,7 @@ export function normalizeConfigName(name?: unknown): string | undefined { "Use letters, numbers, '-' or '_', starting with a letter or number.", ); } - if ((CONFIG_FILE_KEYS as readonly string[]).includes(name) || name === ACTIVE_CONFIG_KEY) { + if (isReservedConfigKey(name)) { throw new BailianError( `Invalid config name "${name}". It conflicts with a config key.`, ExitCode.USAGE, @@ -38,30 +60,48 @@ export function normalizeConfigName(name?: unknown): string | undefined { return name; } -/** 读完整 config.json 原始对象(不经过 `parseConfigFile` 过滤),保留其他命名配置 block。 */ +function configEnvironmentMismatch(path: string): BailianError { + return new BailianError( + `Config file does not match the selected control-plane environment: ${path}. / 配置文件与当前控制面环境不匹配:${path}。`, + ExitCode.USAGE, + ); +} + +function assertConfigEnvironment(raw: unknown, path: string): void { + if (isPreConfigPath(path)) { + if (!isConfigBlock(raw) || raw[CONTROL_ENVIRONMENT_KEY] !== "pre") { + throw configEnvironmentMismatch(path); + } + } else if (isConfigBlock(raw) && Object.hasOwn(raw, CONTROL_ENVIRONMENT_KEY)) { + throw configEnvironmentMismatch(path); + } +} + +/** 读完整配置原始对象(不经过 `parseConfigFile` 过滤),保留其他命名配置 block。 */ function readRawConfigObject( + path: string, onWarning?: (warning: OutputDiagnostic) => void, ): Record { - const path = getConfigPath(); - if (!existsSync(path)) return {}; + let raw: unknown; try { - const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown; - return raw && typeof raw === "object" && !Array.isArray(raw) - ? (raw as Record) - : {}; - } catch (err) { - const e = err as Error; - if (e instanceof SyntaxError || e.message.includes("JSON")) { - onWarning?.({ - code: "CONFIG_CORRUPTED", - message: { - "en-US": "Config file is corrupted; using defaults.", - "zh-CN": "配置文件已损坏,将使用默认配置。", - }, - }); + raw = JSON.parse(readFileSync(path, "utf-8")) as unknown; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return isPreConfigPath(path) ? { [CONTROL_ENVIRONMENT_KEY]: "pre" } : {}; } + if (!(error instanceof SyntaxError)) throw error; + if (isPreConfigPath(path)) throw configEnvironmentMismatch(path); + onWarning?.({ + code: "CONFIG_CORRUPTED", + message: { + "en-US": "Config file is corrupted; using defaults.", + "zh-CN": "配置文件已损坏,将使用默认配置。", + }, + }); return {}; } + assertConfigEnvironment(raw, path); + return isConfigBlock(raw) ? raw : {}; } /** 读取顶层激活元数据;按需校验命名 Profile 必须实际存在。 */ @@ -86,8 +126,8 @@ function readRawConfigBlock(raw: Record, configName?: string): return isConfigBlock(block) ? block : {}; } -export function readConfigFile(configName?: string): ConfigFile { - const raw = readRawConfigObject(); +export function readConfigFile(configName?: string, path = getConfigPath()): ConfigFile { + const raw = readRawConfigObject(path); return parseConfigFile(readRawConfigBlock(raw, configName)); } @@ -95,29 +135,55 @@ export function readConfigFile(configName?: string): ConfigFile { export async function writeConfigFile( data: Record, configName?: string, - options: { activate?: boolean } = {}, + options: { activate?: boolean; path?: string } = {}, ): Promise { - const raw = readRawConfigObject(); - if (configName) { - raw[configName] = data; - } else { - for (const key of Object.keys(raw)) { - if ((CONFIG_FILE_KEYS as readonly string[]).includes(key)) delete raw[key]; + await mutateConfigFile(() => data as ConfigFile, configName, options); +} + +export async function mutateConfigFile( + update: (current: ConfigFile) => ConfigFile | undefined, + configName?: string, + options: { activate?: boolean; path?: string } = {}, +): Promise { + const path = options.path ?? getConfigPath(); + if (configName === CONTROL_ENVIRONMENT_KEY) normalizeConfigName(configName); + await ensureConfigDir(dirname(path)); + return withFileLock(`${path}.lock`, async () => { + const raw = readRawConfigObject(path); + const next = update(parseConfigFile(readRawConfigBlock(raw, configName))); + if (next === undefined) return false; + if (Object.hasOwn(next, CONTROL_ENVIRONMENT_KEY)) { + throw new BailianError( + "control_environment is reserved config metadata. / control_environment 是保留的配置元数据。", + ExitCode.USAGE, + ); } - Object.assign(raw, data); - } - if (options.activate) { - raw[ACTIVE_CONFIG_KEY] = configName ?? "default"; - } - await writeRawConfigObject(raw); + if (configName) raw[configName] = next; + else { + for (const key of CONFIG_FILE_KEYS) delete raw[key]; + Object.assign(raw, next); + } + if (options.activate) raw[ACTIVE_CONFIG_KEY] = configName ?? "default"; + writeRawConfigObject(raw, path); + return true; + }); } -async function writeRawConfigObject(raw: Record): Promise { - await ensureConfigDir(); - const path = getConfigPath(); - const tmp = path + ".tmp"; - writeFileSync(tmp, JSON.stringify(raw, null, 2) + "\n", { mode: 0o600 }); - renameSync(tmp, path); +function writeRawConfigObject(raw: Record, path: string): void { + assertConfigEnvironment(raw, path); + const temporaryPath = `${path}.${randomUUID()}.tmp`; + const handle = openSync(temporaryPath, "wx", 0o600); + try { + try { + writeFileSync(handle, JSON.stringify(raw, null, 2) + "\n"); + fsyncSync(handle); + } finally { + closeSync(handle); + } + renameSync(temporaryPath, path); + } finally { + if (existsSync(temporaryPath)) unlinkSync(temporaryPath); + } } /** 全量配置快照:顶层默认配置 + 各命名 profile。 */ @@ -132,14 +198,13 @@ export interface ConfigProfiles { /** * 读取全部 profile:顶层默认配置与各命名 block。 - * 命名 block = raw 中不属于 `CONFIG_FILE_KEYS`、且值为普通对象的项。 + * 命名 block = raw 中不属于默认配置字段或保留元数据、且值为普通对象的项。 */ -export function readConfigProfiles(): ConfigProfiles { - const raw = readRawConfigObject(); +export function readConfigProfiles(path = getConfigPath()): ConfigProfiles { + const raw = readRawConfigObject(path); const named: Record = {}; for (const [key, value] of Object.entries(raw)) { - if ((CONFIG_FILE_KEYS as readonly string[]).includes(key) || key === ACTIVE_CONFIG_KEY) - continue; + if (isReservedConfigKey(key)) continue; if (isConfigBlock(value)) { named[key] = parseConfigFile(value); } @@ -164,31 +229,48 @@ function resolveConfigProfileActivation(raw: Record, name?: unk } /** 校验激活目标并返回规范化展示名;不写配置。 */ -export function validateConfigProfileActivation(name?: unknown): string { - return resolveConfigProfileActivation(readRawConfigObject(), name); +export function validateConfigProfileActivation(name?: unknown, path = getConfigPath()): string { + return resolveConfigProfileActivation(readRawConfigObject(path), name); } /** 将已存在的命名 Profile(或 default)设为持久化激活项。 */ -export async function activateConfigProfile(name?: unknown): Promise { - const raw = readRawConfigObject(); - const active = resolveConfigProfileActivation(raw, name); - raw[ACTIVE_CONFIG_KEY] = active; - await writeRawConfigObject(raw); - return active; +export async function activateConfigProfile( + name?: unknown, + path = getConfigPath(), +): Promise { + await ensureConfigDir(dirname(path)); + return withFileLock(`${path}.lock`, async () => { + const raw = readRawConfigObject(path); + const active = resolveConfigProfileActivation(raw, name); + raw[ACTIVE_CONFIG_KEY] = active; + writeRawConfigObject(raw, path); + return active; + }); } /** 删除一个命名 profile block;存在才删并回写,返回是否有变更。 */ -export async function deleteConfigProfile(name?: unknown): Promise { +export async function deleteConfigProfile( + name?: unknown, + path = getConfigPath(), +): Promise { const configName = normalizeConfigName(name); if (!configName) { throw new BailianError("Cannot delete the default profile.", ExitCode.USAGE); } - const raw = readRawConfigObject(); - if (!isConfigBlock(raw[configName])) return false; - delete raw[configName]; - if (readStoredActiveConfigName(raw, false) === configName) raw[ACTIVE_CONFIG_KEY] = "default"; - await writeRawConfigObject(raw); - return true; + await ensureConfigDir(dirname(path)); + return withFileLock(`${path}.lock`, async () => { + const raw = readRawConfigObject(path); + if (!isConfigBlock(raw[configName])) return false; + if (parseConfigFile(raw[configName]).aliyun_oauth) + throw new BailianError( + "Remove the OAuth session before deleting this profile. / 删除此配置前请先退出 OAuth 会话。", + ExitCode.USAGE, + ); + delete raw[configName]; + if (readStoredActiveConfigName(raw, false) === configName) raw[ACTIVE_CONFIG_KEY] = "default"; + writeRawConfigObject(raw, path); + return true; + }); } /** @@ -201,8 +283,10 @@ export interface ResolutionSources { env: NodeJS.ProcessEnv; /** 当前命名配置名(`--config ` 解析后);未指定或 `default` 时为 undefined。 */ configName?: string; - /** 实际 config.json 路径(不受 configName 影响,一直是同一个文件)。 */ + /** 所选环境的配置文件路径,不受 configName 影响。 */ configPath?: string; + /** These sources were selected for the pre-release control plane. */ + preControlPlane?: PreControlPlane; } export interface ApiKeyResolutionSourceSelection { @@ -237,27 +321,47 @@ export function selectApiKeyResolutionSources( return { sources: { ...sources, - file: readConfigFile(), + file: readConfigFile(undefined, sources.configPath ?? getConfigPath(sources.preControlPlane)), configName: undefined, }, fallbackFrom: sources.configName, }; } +function isInheritedControlEnvKey(name: string): boolean { + // Windows treats environment variable names as case-insensitive. + const key = name.toUpperCase(); + return ( + key.startsWith("BAILIAN_ACCESS_KEY_") || + key.startsWith("ALIBABA_CLOUD_ACCESS_KEY_") || + key === "BAILIAN_SECURITY_TOKEN" || + key === "ALIBABA_CLOUD_SECURITY_TOKEN" || + key === "BAILIAN_WORKSPACE_ID" + ); +} + export function buildSources( flags: Partial, onWarning?: (warning: OutputDiagnostic) => void, + preControlPlane?: PreControlPlane, ): ResolutionSources { - const raw = readRawConfigObject(onWarning); - const configExplicit = flags.config !== undefined; - const activeConfigName = readStoredActiveConfigName(raw, !configExplicit); - const configName = configExplicit ? normalizeConfigName(flags.config) : activeConfigName; + const configPath = getConfigPath(preControlPlane); + const raw = readRawConfigObject(configPath, onWarning); + const configName = + flags.config !== undefined + ? normalizeConfigName(flags.config) + : readStoredActiveConfigName(raw, true); return { flags, file: parseConfigFile(readRawConfigBlock(raw, configName)), - env: process.env, + env: preControlPlane + ? Object.fromEntries( + Object.entries(process.env).filter(([name]) => !isInheritedControlEnvKey(name)), + ) + : process.env, configName, - configPath: getConfigPath(), + configPath, + ...(preControlPlane ? { preControlPlane } : {}), }; } @@ -317,7 +421,8 @@ export function buildSettings(s: ResolutionSources): Settings { } return { - configPath: s.configPath ?? getConfigPath(), + ...(s.preControlPlane ? { preControlPlane: s.preControlPlane } : {}), + configPath: s.configPath ?? getConfigPath(s.preControlPlane), configName: s.configName, recoveryConfigName: resolveRecoveryConfigName(s), ...buildOutputSettings(s), diff --git a/packages/core/src/config/paths.ts b/packages/core/src/config/paths.ts index 78e3f45e2..451ae063a 100644 --- a/packages/core/src/config/paths.ts +++ b/packages/core/src/config/paths.ts @@ -1,23 +1,30 @@ import { homedir } from "os"; -import { join } from "path"; +import { basename, join } from "path"; +import type { PreControlPlane } from "./control-plane.ts"; const CONFIG_DIR_NAME = ".bailian"; +const PRE_CONFIG_FILE_NAME = "control-pre.json"; export function getConfigDir(): string { if (process.env.BAILIAN_CONFIG_DIR) return process.env.BAILIAN_CONFIG_DIR; return join(homedir(), CONFIG_DIR_NAME); } -export function getConfigPath(): string { - return join(getConfigDir(), "config.json"); +export function getConfigPath(preControlPlane?: PreControlPlane): string { + const dir = getConfigDir(); + return preControlPlane ? join(dir, "pre", PRE_CONFIG_FILE_NAME) : join(dir, "config.json"); +} + +/** The reserved basename also identifies a pre-release file passed by explicit path. */ +export function isPreConfigPath(path: string): boolean { + return basename(path) === PRE_CONFIG_FILE_NAME; } export function getCredentialsPath(): string { return join(getConfigDir(), "credentials.json"); } -export async function ensureConfigDir(): Promise { - const dir = getConfigDir(); +export async function ensureConfigDir(dir = getConfigDir()): Promise { const fs = await import("fs/promises"); await fs.mkdir(dir, { recursive: true, mode: 0o700 }); // `mkdir`'s `mode` only applies to directories it creates (and is masked by diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts index 5b0531195..b803f36db 100644 --- a/packages/core/src/config/schema.ts +++ b/packages/core/src/config/schema.ts @@ -1,4 +1,7 @@ import { normalizeModelBaseUrl } from "./model-base-url.ts"; +import { parseAliyunOAuthProfile } from "../auth/aliyun-config.ts"; +import type { AliyunOAuthProfile } from "../auth/aliyun-types.ts"; +import type { PreControlPlane } from "./control-plane.ts"; export const REGIONS = { cn: "https://dashscope.aliyuncs.com", @@ -25,6 +28,7 @@ export interface ConfigFile { api_key?: string; /** OAuth-style token from `bl auth login --console` callback; sent as `Authorization: Bearer …` */ access_token?: string; + aliyun_oauth?: AliyunOAuthProfile; /** Alibaba Cloud OpenAPI AccessKey ID from `bl auth login --open-api`. */ access_key_id?: string; /** Alibaba Cloud OpenAPI AccessKey secret from `bl auth login --open-api`. */ @@ -57,6 +61,7 @@ export const CONFIG_FILE_KEYS = [ "language", "api_key", "access_token", + "aliyun_oauth", "access_key_id", "access_key_secret", "security_token", @@ -125,6 +130,7 @@ export function parseConfigFile(raw: unknown): ConfigFile { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const obj = raw as Record; const out: ConfigFile = {}; + if (obj.aliyun_oauth !== undefined) out.aliyun_oauth = parseAliyunOAuthProfile(obj.aliyun_oauth); if ( typeof obj.language === "string" && @@ -218,6 +224,8 @@ export interface Identity { * 真实调用走 ConsoleCredential(同链解析,受控重叠)。 */ export interface Settings { + /** Control-plane routing only; model configuration may still come from the production file. */ + preControlPlane?: PreControlPlane; configPath?: string; configName?: string; /** diff --git a/packages/core/src/config/store.ts b/packages/core/src/config/store.ts index 998d865e7..adbc5d3e2 100644 --- a/packages/core/src/config/store.ts +++ b/packages/core/src/config/store.ts @@ -4,7 +4,7 @@ import { readConfigFile, readConfigProfiles, validateConfigProfileActivation, - writeConfigFile, + mutateConfigFile, type ConfigProfiles, } from "./loader.ts"; import { getConfigPath } from "./paths.ts"; @@ -29,27 +29,43 @@ export interface ConfigStore { path: string; } -export function makeConfigStore(configName?: string): ConfigStore { +export function makeConfigStore( + configName?: string, + configurationPath = getConfigPath(), +): ConfigStore { return { - read: () => readConfigFile(configName), + read: () => readConfigFile(configName, configurationPath), async write(patch) { - const existing = readConfigFile(configName) as Record; - for (const [key, value] of Object.entries(patch)) { - if (value === undefined) delete existing[key]; - else existing[key] = key === "base_url" ? normalizeModelBaseUrl(String(value)) : value; - } - await writeConfigFile(existing, configName); + await mutateConfigFile( + (current) => { + const existing = { ...current } as Record; + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) delete existing[key]; + else + existing[key] = key === "base_url" ? normalizeModelBaseUrl(value as string) : value; + } + return existing as ConfigFile; + }, + configName, + { path: configurationPath }, + ); }, async unset(keys) { - const existing = readConfigFile(configName) as Record; - for (const key of keys) delete existing[key]; - await writeConfigFile(existing, configName); + await mutateConfigFile( + (current) => { + const existing = { ...current }; + for (const key of keys) delete existing[key]; + return existing; + }, + configName, + { path: configurationPath }, + ); }, - profiles: () => readConfigProfiles(), - activate: (name) => activateConfigProfile(name), - validateActivation: (name) => validateConfigProfileActivation(name), + profiles: () => readConfigProfiles(configurationPath), + activate: (name) => activateConfigProfile(name, configurationPath), + validateActivation: (name) => validateConfigProfileActivation(name, configurationPath), get path() { - return getConfigPath(); + return configurationPath; }, }; } diff --git a/packages/core/src/console/gateway.ts b/packages/core/src/console/gateway.ts index 6f46b779d..1c8ab8fa2 100644 --- a/packages/core/src/console/gateway.ts +++ b/packages/core/src/console/gateway.ts @@ -1,9 +1,11 @@ import { CredentialError } from "../errors/credential.ts"; +import { normalizeOAuthUrl } from "../auth/aliyun-config.ts"; import { debugRequest, debugResponse } from "../client/diagnostics.ts"; import type { HttpDeps } from "../client/http.ts"; import { httpTransport } from "../client/transport.ts"; import type { Settings } from "../config/schema.ts"; -import { BailianError } from "../errors/base.ts"; +import { requirePreConsoleGateway, type PreControlPlane } from "../config/control-plane.ts"; +import { BailianError, UsageError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; const GATEWAY_PRODUCT = "sfm_bailian"; @@ -42,23 +44,43 @@ function resolveGateway(region: string, site: ConsoleSite): ConsoleGatewayInfo { return REGION_GATEWAYS[region]?.[site] ?? REGION_GATEWAYS["cn-beijing"]![site]; } +export function resolveConsoleGatewayOrigin( + region: string, + site: ConsoleSite, + pre?: PreControlPlane, +): string { + return pre + ? requirePreConsoleGateway(pre, { region, site }) + : `https://${resolveGateway(region, site).csGateway}`; +} + /** * Resolved console gateway settings (same defaults as {@link callConsoleGateway}). * 参数只需 settings 的 console 三元组;dry-run 展示分支直接传 settings。 */ export function effectiveConsoleGatewayConfig( - config: Pick, + config: Pick< + Settings, + "consoleRegion" | "consoleSite" | "consoleSwitchAgent" | "preControlPlane" + >, ): { consoleRegion: string; consoleSite: ConsoleSite; consoleSwitchAgent?: number; + environment?: "pre"; + consoleGateway?: string | null; } { const consoleRegion = config.consoleRegion ?? "cn-beijing"; const consoleSite = config.consoleSite ?? "domestic"; const consoleSwitchAgent = config.consoleSwitchAgent; - return consoleSwitchAgent != null - ? { consoleRegion, consoleSite, consoleSwitchAgent } - : { consoleRegion, consoleSite }; + return { + consoleRegion, + consoleSite, + ...(consoleSwitchAgent != null ? { consoleSwitchAgent } : {}), + ...(config.preControlPlane + ? { environment: "pre", consoleGateway: config.preControlPlane.consoleGateway ?? null } + : {}), + }; } export interface ConsoleGatewayRequest { @@ -75,7 +97,10 @@ export type ConsoleCall = (api: string, data: Record) => Promis * as `listFoundationModels` — no console login required. */ export function anonymousConsoleCall( - config: Pick, + config: Pick< + Settings, + "consoleRegion" | "consoleSite" | "consoleSwitchAgent" | "timeout" | "preControlPlane" + >, options: Pick & { recoveryHint?: string } = {}, ): ConsoleCall { const eff = effectiveConsoleGatewayConfig(config); @@ -84,7 +109,7 @@ export function anonymousConsoleCall( { region: eff.consoleRegion, site: eff.consoleSite, switchAgent: eff.consoleSwitchAgent }, config.timeout, { api, data }, - options, + { ...options, preControlPlane: config.preControlPlane }, ); } @@ -126,6 +151,7 @@ function buildGatewayParams( * ConsoleCredential;公共目录类 API(如 advisor 的模型目录)可不带 token 匿名调用。 */ export interface ConsoleGatewayTarget { + gateway?: string; region: string; site: ConsoleSite; switchAgent?: number; @@ -136,10 +162,21 @@ export async function callConsoleGateway( target: ConsoleGatewayTarget, timeoutSec: number, { api, data }: ConsoleGatewayRequest, - options: Pick & { recoveryHint?: string } = {}, + options: Pick & { + recoveryHint?: string; + preControlPlane?: PreControlPlane; + } = {}, ): Promise { const resolved = resolveGateway(target.region, target.site); - const gatewayBase = `https://${resolved.csGateway}`; + const explicitGateway = target.gateway ? normalizeOAuthUrl(target.gateway, true) : undefined; + const pre = options.preControlPlane; + const gatewayBase = pre + ? requirePreConsoleGateway(pre, target) + : (explicitGateway ?? resolveConsoleGatewayOrigin(target.region, target.site)); + if (pre && explicitGateway && explicitGateway !== gatewayBase) + throw new UsageError( + "The Console gateway does not match the pre-release route. / 控制台网关与预发路由不匹配。", + ); const action = resolved.action; const params = buildGatewayParams(api, data, target.switchAgent); @@ -159,6 +196,7 @@ export async function callConsoleGateway( method: "POST", headers, body: body.toString(), + ...(pre || target.gateway ? { redirect: "error" as const } : {}), signal: AbortSignal.timeout(timeoutMs), }); diff --git a/packages/core/src/console/index.ts b/packages/core/src/console/index.ts index 07d732371..eede7d4e2 100644 --- a/packages/core/src/console/index.ts +++ b/packages/core/src/console/index.ts @@ -9,6 +9,7 @@ export { anonymousConsoleCall, callConsoleGateway, effectiveConsoleGatewayConfig, + resolveConsoleGatewayOrigin, } from "./gateway.ts"; export type { ModelListParams, diff --git a/packages/core/src/errors/credential.ts b/packages/core/src/errors/credential.ts index d40ff527b..48529c09d 100644 --- a/packages/core/src/errors/credential.ts +++ b/packages/core/src/errors/credential.ts @@ -8,7 +8,11 @@ export type CredentialFailure = | "missing-openapi-pair" | "incomplete-openapi-flag" | "incomplete-openapi-env" - | "incomplete-openapi-config"; + | "incomplete-openapi-config" + | "aliyun-oauth-session" + | "missing-aliyun-session" + | "aliyun-refresh-uncertain" + | "changed-openapi-identity"; /** Local credential failure facts; CLI recovery instructions belong to the host. */ export class CredentialError extends BailianError { diff --git a/packages/core/src/utils/file-lock.ts b/packages/core/src/utils/file-lock.ts new file mode 100644 index 000000000..98044ee1a --- /dev/null +++ b/packages/core/src/utils/file-lock.ts @@ -0,0 +1,81 @@ +import { randomUUID } from "node:crypto"; +import { mkdir, open, readFile, unlink } from "node:fs/promises"; +import { dirname } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { BailianError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; + +export async function withFileLock( + path: string, + operation: () => Promise, + timeout = 30_000, +): Promise { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + const ownership = JSON.stringify({ pid: process.pid, id: randomUUID() }); + const deadline = Date.now() + timeout; + for (;;) { + try { + const handle = await open(path, "wx", 0o600); + try { + await handle.writeFile(ownership); + } finally { + await handle.close(); + } + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + const previous = await readFile(path, "utf8").catch((readError: NodeJS.ErrnoException) => { + if (readError.code === "ENOENT") return undefined; + throw readError; + }); + if (previous === undefined) continue; + let owner: { pid?: unknown } = {}; + try { + owner = JSON.parse(previous); + } catch { + // A live writer may not have finished writing its ownership record. + } + if (typeof owner.pid === "number" && Number.isInteger(owner.pid) && owner.pid > 0) { + try { + process.kill(owner.pid, 0); + } catch (ownerError) { + if ((ownerError as NodeJS.ErrnoException).code === "ESRCH") { + const recoveryPath = `${path}.recovery`; + const recovery = await open(recoveryPath, "wx", 0o600).catch( + (recoveryError: NodeJS.ErrnoException) => { + if (recoveryError.code === "EEXIST") return undefined; + throw recoveryError; + }, + ); + if (recovery) { + try { + if ((await readFile(path, "utf8").catch(() => undefined)) === previous) { + await unlink(path).catch((removeError: NodeJS.ErrnoException) => { + if (removeError.code !== "ENOENT") throw removeError; + }); + } + } finally { + await recovery.close(); + await unlink(recoveryPath); + } + } + } + } + } + if (Date.now() >= deadline) { + throw new BailianError( + "Timed out waiting for the credential/configuration lock. / 等待凭据或配置锁超时。", + ExitCode.TIMEOUT, + ); + } + await delay(25); + } + } + try { + return await operation(); + } finally { + if ((await readFile(path, "utf8").catch(() => undefined)) === ownership) { + await unlink(path); + } + } +} diff --git a/packages/core/tests/aliyun-oauth.test.ts b/packages/core/tests/aliyun-oauth.test.ts new file mode 100644 index 000000000..6c35cf363 --- /dev/null +++ b/packages/core/tests/aliyun-oauth.test.ts @@ -0,0 +1,529 @@ +import { createHash } from "node:crypto"; +import { + afterEach, + beforeEach, + describe, + expect, + test, + vi, + type MockInstance, +} from "vite-plus/test"; +import { + aliyunAuthorizationUrl, + createOAuthProofKey, + exchangeAliyunCode, + exchangeAliyunSts, + parseAliyunCallback, + refreshAliyunTokens, + revokeAliyunTokens, + type AliyunOAuthDeps, +} from "../src/auth/aliyun-oauth.ts"; +import { httpTransport } from "../src/client/transport.ts"; +import { BailianError, UsageError } from "../src/errors/base.ts"; +import { ExitCode } from "../src/errors/codes.ts"; + +const NOW = Date.UTC(2026, 0, 1); +const PROFILE = { + client_id: "fixture-native-client", + scope: "openid /internal/bailian/cli", + authorization_url: "https://authorize.example.test/authorize?audience=fixture", + oauth_base_url: "https://oauth.example.test", +}; +const REDIRECT = "http://127.0.0.1:43123/callback"; +const CODE = "fixture-code+with&encoding"; +const VERIFIER = "fixture-verifier-with-encoding+&"; +const ACCESS = "fixture-oauth-access"; +const REFRESH = "fixture-oauth-refresh"; +const TOKEN = { + access_token: ACCESS, + refresh_token: REFRESH, + expires_in: 3600, + token_type: "Bearer", + scope: PROFILE.scope, +}; +const STS = { + accessKeyId: "fixture-sts-id", + accessKeySecret: "fixture-sts-secret", + securityToken: "fixture-sts-token", + expiration: new Date(NOW + 3600_000).toISOString(), +}; +const PASCAL_CASE_STS = { + AccessKeyId: STS.accessKeyId, + AccessKeySecret: STS.accessKeySecret, + SecurityToken: STS.securityToken, + Expiration: STS.expiration, +}; + +function response(data: unknown, status = 200, headers: Record = {}) { + return new Response(JSON.stringify(data), { status, headers }); +} + +const debug = vi.fn(); +const deps: AliyunOAuthDeps = { + identity: { + binName: "fixture-cli", + version: "0.0.0-test", + clientName: "fixture-client", + npmPackage: "fixture-package", + }, + timeout: 5, + now: () => NOW, + debug, +}; +let transport: MockInstance; +beforeEach(() => { + debug.mockClear(); + // Every protocol request is intercepted; no real OAuth/API or OS secret backend is used. + transport = vi.spyOn(httpTransport, "fetch").mockRejectedValue(new Error("Unexpected request")); +}); +afterEach(() => vi.restoreAllMocks()); + +function request() { + expect(transport).toHaveBeenCalledTimes(1); + const [endpoint, init] = transport.mock.calls[0]!; + expect(init?.method).toBe("POST"); + expect(init?.redirect).toBe("error"); + expect(init?.signal).toBeInstanceOf(AbortSignal); + const headers = new Headers(init?.headers); + expect(headers.get("x-dashscope-openapisource")).toBe("BailianCLI"); + expect(JSON.parse(headers.get("x-dashscope-source-config")!)).toMatchObject({ + tags: { t2: "fixture-cli", t3: "0.0.0-test" }, + }); + expect(typeof endpoint).toBe("string"); + if (typeof endpoint !== "string") throw new Error("OAuth endpoint must be a string"); + return { endpoint, init, headers }; +} + +function formFields(init?: RequestInit) { + expect(typeof init?.body).toBe("string"); + if (typeof init?.body !== "string") throw new Error("OAuth form body must be a string"); + return Object.fromEntries(new URLSearchParams(init.body)); +} + +async function caughtError(operation: Promise): Promise { + const error: unknown = await operation.then( + () => undefined, + (caught: unknown) => caught, + ); + expect(error).toBeInstanceOf(BailianError); + return error as BailianError; +} + +function expectNoSecrets(error?: BailianError) { + const visible = JSON.stringify({ diagnostics: debug.mock.calls, error: error?.toJSON() }); + for (const secret of [CODE, VERIFIER, ACCESS, REFRESH, STS.accessKeySecret, STS.securityToken]) { + expect(visible).not.toContain(secret); + } +} + +describe("Aliyun OAuth authorization and callback", () => { + test("creates independent high-entropy state and RFC 7636 S256 proof keys", () => { + const first = createOAuthProofKey(); + const second = createOAuthProofKey(); + for (const proof of [first, second]) { + expect(proof.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(proof.state).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(proof.state).not.toBe(proof.verifier); + expect(proof.challenge).toBe( + createHash("sha256").update(proof.verifier, "ascii").digest("base64url"), + ); + } + expect(first.state).not.toBe(second.state); + expect(first.verifier).not.toBe(second.verifier); + expect(transport).not.toHaveBeenCalled(); + }); + + test("authorization URL has exact public fields, preserves audience and never exposes verifier", () => { + const proof = createOAuthProofKey(); + const url = new URL(aliyunAuthorizationUrl(PROFILE, REDIRECT, proof)); + expect(url.origin + url.pathname).toBe("https://authorize.example.test/authorize"); + expect(Object.fromEntries(url.searchParams)).toEqual({ + audience: "fixture", + response_type: "code", + client_id: PROFILE.client_id, + scope: PROFILE.scope, + redirect_uri: REDIRECT, + state: proof.state, + code_challenge: proof.challenge, + code_challenge_method: "S256", + }); + expect(url.toString()).not.toContain(proof.verifier); + expect(url.searchParams.has("code_verifier")).toBe(false); + }); + + test("overwrites existing reserved query fields rather than appending duplicates", () => { + const proof = createOAuthProofKey(); + const url = new URL( + aliyunAuthorizationUrl( + { + ...PROFILE, + authorization_url: `${PROFILE.authorization_url}&state=old&state=duplicate&code_challenge=old`, + }, + REDIRECT, + proof, + ), + ); + expect(url.searchParams.getAll("state")).toEqual([proof.state]); + expect(url.searchParams.getAll("code_challenge")).toEqual([proof.challenge]); + }); + + test("accepts a single matching state and returns decoded code verbatim", () => { + const url = new URL(REDIRECT); + url.searchParams.set("state", "fixture-state"); + url.searchParams.set("code", CODE); + expect(parseAliyunCallback(url, "fixture-state")).toBe(CODE); + }); + + test.each([ + "code=fixture-code", + "state=wrong&code=fixture-code", + "state=fixture-state&state=fixture-state&code=fixture-code", + "state=fixture-state&state=wrong&code=fixture-code", + "state=fixture-state", + "state=fixture-state&code=", + "state=fixture-state&code=%20%09", + "state=fixture-state&code=first&code=second", + ])("rejects malformed callback %s without requests", (query) => { + expect(() => parseAliyunCallback(new URL(`${REDIRECT}?${query}`), "fixture-state")).toThrow( + UsageError, + ); + expect(transport).not.toHaveBeenCalled(); + }); + + test("authorization denial is generic and does not echo callback secrets", () => { + let failure: unknown; + try { + parseAliyunCallback( + new URL( + `${REDIRECT}?state=fixture-state&error=access_denied&error_description=${REFRESH}&code=${ACCESS}`, + ), + "fixture-state", + ); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(BailianError); + expect(failure).toMatchObject({ exitCode: ExitCode.GENERAL }); + expectNoSecrets(failure as BailianError); + }); + + test("invalid state is rejected before interpreting an error callback", () => { + expect(() => + parseAliyunCallback(new URL(`${REDIRECT}?state=wrong&error=access_denied`), "fixture-state"), + ).toThrow(UsageError); + }); +}); + +describe("Aliyun OAuth token and STS wire protocol", () => { + test("code exchange POSTs only native OAuth form fields, never client_secret or Bearer", async () => { + transport.mockResolvedValue(response(TOKEN)); + expect(await exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps)).toEqual({ + accessToken: ACCESS, + refreshToken: REFRESH, + accessTokenExpiresAt: NOW + 3600_000, + }); + const sent = request(); + expect(sent.endpoint).toBe(`${PROFILE.oauth_base_url}/v1/token`); + expect(sent.headers.get("content-type")).toBe("application/x-www-form-urlencoded"); + expect(sent.headers.has("authorization")).toBe(false); + expect(formFields(sent.init)).toEqual({ + grant_type: "authorization_code", + client_id: PROFILE.client_id, + code: CODE, + redirect_uri: REDIRECT, + code_verifier: VERIFIER, + }); + expectNoSecrets(); + }); + + test("refresh POSTs old RT and retains it when rotation field is omitted", async () => { + transport.mockResolvedValue( + response({ access_token: ACCESS, expires_in: "120", token_type: "Bearer" }), + ); + expect(await refreshAliyunTokens(PROFILE, REFRESH, deps)).toEqual({ + accessToken: ACCESS, + refreshToken: REFRESH, + accessTokenExpiresAt: NOW + 120_000, + }); + const sent = request(); + expect(sent.endpoint).toBe(`${PROFILE.oauth_base_url}/v1/token`); + expect(sent.headers.get("content-type")).toBe("application/x-www-form-urlencoded"); + expect(sent.headers.has("authorization")).toBe(false); + expect(formFields(sent.init)).toEqual({ + grant_type: "refresh_token", + client_id: PROFILE.client_id, + refresh_token: REFRESH, + }); + expectNoSecrets(); + }); + + test("refresh accepts and returns a rotated RT", async () => { + transport.mockResolvedValue(response({ ...TOKEN, refresh_token: "fixture-rotated-refresh" })); + expect(await refreshAliyunTokens(PROFILE, REFRESH, deps)).toMatchObject({ + refreshToken: "fixture-rotated-refresh", + }); + }); + + test.each([ + { casing: "camelCase", payload: STS }, + { casing: "PascalCase", payload: PASCAL_CASE_STS }, + ])("normalizes $casing STS fields from an empty-body Bearer POST", async ({ payload }) => { + transport.mockResolvedValue(response(payload)); + expect(await exchangeAliyunSts(PROFILE, ACCESS, deps)).toEqual({ + accessKeyId: STS.accessKeyId, + accessKeySecret: STS.accessKeySecret, + securityToken: STS.securityToken, + expiresAt: NOW + 3600_000, + }); + const sent = request(); + expect(sent.endpoint).toBe(`${PROFILE.oauth_base_url}/v1/exchange`); + expect(sent.headers.get("authorization")).toBe(`Bearer ${ACCESS}`); + expect(sent.headers.get("content-type")).toBe("application/json"); + expect(sent.init?.body).toBeUndefined(); + expect(new URL(sent.endpoint).search).toBe(""); + expectNoSecrets(); + }); + + test("revoke sends only client_id and RT in a form and accepts an empty 204", async () => { + transport.mockResolvedValue(new Response(null, { status: 204 })); + await revokeAliyunTokens(PROFILE, REFRESH, deps); + const sent = request(); + expect(sent.endpoint).toBe(`${PROFILE.oauth_base_url}/v1/revoke`); + expect(sent.headers.get("content-type")).toBe("application/x-www-form-urlencoded"); + expect(sent.headers.has("authorization")).toBe(false); + expect(formFields(sent.init)).toEqual({ + client_id: PROFILE.client_id, + token: REFRESH, + }); + expectNoSecrets(); + }); +}); + +describe("token, scope and expiry validation", () => { + test.each( + [ + { access_token: undefined }, + { access_token: "" }, + { access_token: " " }, + { access_token: 42 }, + { refresh_token: undefined }, + { refresh_token: "" }, + { refresh_token: " " }, + { refresh_token: null }, + { refresh_token: 42 }, + { expires_in: undefined }, + { expires_in: 0 }, + { expires_in: -1 }, + { expires_in: "NaN" }, + { expires_in: "Infinity" }, + { expires_in: "invalid" }, + { token_type: "Basic" }, + { token_type: "bearer" }, + ].map((patch) => ({ patch, field: Object.keys(patch)[0], value: Object.values(patch)[0] })), + )("rejects invalid login token $field=$value", async ({ patch }) => { + transport.mockResolvedValue(response({ ...TOKEN, ...patch })); + const error = await caughtError(exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps)); + expect(error.exitCode).toBe(ExitCode.GENERAL); + expectNoSecrets(error); + }); + + test.each([true, [], [1], Number.MAX_VALUE].map((expiresIn) => ({ expiresIn })))( + "rejects nonnumeric or overflowing TTL $expiresIn", + async ({ expiresIn }) => { + transport.mockResolvedValue(response({ ...TOKEN, expires_in: expiresIn })); + const error = await caughtError(exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps)); + expect(error.exitCode).toBe(ExitCode.GENERAL); + expectNoSecrets(error); + }, + ); + + test("supports positive subsecond TTL against injected time", async () => { + transport.mockResolvedValue(response({ ...TOKEN, expires_in: 0.5 })); + expect(await exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps)).toMatchObject({ + accessTokenExpiresAt: NOW + 500, + }); + }); + + test.each(["openid", "/internal/bailian/cli", "", "openid /internal/bailian/cli-extra"])( + "rejects insufficient explicitly granted scope %j", + async (scope) => { + transport.mockResolvedValue(response({ ...TOKEN, scope })); + const error = await caughtError(exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps)); + expect(error.message).toContain("scope"); + expectNoSecrets(error); + }, + ); + + test("scope comparison is set-based and allows an explicitly granted superset", async () => { + transport.mockResolvedValue( + response({ ...TOKEN, scope: " extra\t/internal/bailian/cli\nopenid " }), + ); + await expect( + exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps), + ).resolves.toMatchObject({ accessToken: ACCESS }); + }); + + test("omitted scope and token_type remain compatible with token endpoint responses", async () => { + transport.mockResolvedValue(response({ ...TOKEN, scope: undefined, token_type: undefined })); + await expect( + exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps), + ).resolves.toMatchObject({ refreshToken: REFRESH }); + }); + + test.each( + [ + { accessKeyId: undefined }, + { accessKeyId: "" }, + { accessKeyId: " " }, + { accessKeySecret: undefined }, + { accessKeySecret: "" }, + { accessKeySecret: 42 }, + { securityToken: undefined }, + { securityToken: " " }, + { expiration: undefined }, + { expiration: "not-a-date" }, + { expiration: NOW + 3600_000 }, + { expiration: new Date(NOW).toISOString() }, + { expiration: new Date(NOW - 1).toISOString() }, + ].map((patch) => ({ patch, field: Object.keys(patch)[0], value: Object.values(patch)[0] })), + )("rejects invalid STS response $field=$value", async ({ patch }) => { + transport.mockResolvedValue(response({ ...STS, ...patch })); + const error = await caughtError(exchangeAliyunSts(PROFILE, ACCESS, deps)); + expect(error.exitCode).toBe(ExitCode.GENERAL); + expectNoSecrets(error); + }); + + test.each([ + { reason: "blank secret", patch: { AccessKeySecret: " " } }, + { reason: "non-string token", patch: { SecurityToken: 42 } }, + { reason: "invalid expiration", patch: { Expiration: "not-a-date" } }, + { reason: "expired credential", patch: { Expiration: new Date(NOW).toISOString() } }, + { + reason: "mixed field names", + patch: { AccessKeySecret: undefined, accessKeySecret: STS.accessKeySecret }, + }, + ])("rejects PascalCase STS response with $reason", async ({ patch }) => { + transport.mockResolvedValue(response({ ...PASCAL_CASE_STS, ...patch })); + const error = await caughtError(exchangeAliyunSts(PROFILE, ACCESS, deps)); + expect(error.exitCode).toBe(ExitCode.GENERAL); + expectNoSecrets(error); + }); + + test("accepts STS expiry one millisecond beyond now", async () => { + transport.mockResolvedValue(response({ ...STS, expiration: new Date(NOW + 1).toISOString() })); + await expect(exchangeAliyunSts(PROFILE, ACCESS, deps)).resolves.toMatchObject({ + expiresAt: NOW + 1, + }); + }); +}); + +describe("OAuth failures preserve API context without credentials", () => { + test.each([ + { + status: 400, + data: { + error: "invalid_grant", + error_description: "Service rejected this grant verbatim", + requestId: "fixture-request", + }, + }, + { + status: 200, + data: { + Success: false, + Code: "FixtureDenied", + Message: "Service business error verbatim", + RequestId: "fixture-request", + }, + }, + { status: 503, data: { message: "Service unavailable verbatim" } }, + ])("passes service message and context through for HTTP $status", async ({ status, data }) => { + transport.mockResolvedValue( + response(data, status, { "x-request-id": "fixture-header-request" }), + ); + const error = await caughtError(refreshAliyunTokens(PROFILE, REFRESH, deps)); + expect(error.exitCode).toBe(ExitCode.GENERAL); + expect(error.message).toBe( + "error_description" in data + ? data.error_description + : "Message" in data + ? data.Message + : data.message, + ); + expect(error.api).toEqual({ + httpStatus: status, + apiCode: "error" in data ? data.error : "Code" in data ? data.Code : undefined, + requestId: + "requestId" in data || "RequestId" in data ? "fixture-request" : "fixture-header-request", + }); + expect(error.toJSON().error).toMatchObject({ http_status: status, message: error.message }); + expectNoSecrets(error); + }); + + test.each(["code", "refresh", "sts"] as const)( + "redacts reflected %s secrets in service errors and diagnostics", + async (operation) => { + const reflected = + operation === "code" ? [CODE, VERIFIER] : operation === "refresh" ? [REFRESH] : [ACCESS]; + transport.mockResolvedValue( + response( + { + error: "fixture_error", + error_description: `Rejected ${reflected.join(" / ")} twice ${reflected.join(" / ")}`, + }, + 400, + ), + ); + const error = await caughtError( + operation === "code" + ? exchangeAliyunCode(PROFILE, CODE, VERIFIER, REDIRECT, deps) + : operation === "refresh" + ? refreshAliyunTokens(PROFILE, REFRESH, deps) + : exchangeAliyunSts(PROFILE, ACCESS, deps), + ); + expect(error.message).toBe( + `Rejected ${reflected.map(() => "[REDACTED]").join(" / ")} twice ${reflected.map(() => "[REDACTED]").join(" / ")}`, + ); + expectNoSecrets(error); + }, + ); + + test.each([null, [], "fixture-response-secret", 42].map((data) => ({ data })))( + "rejects nonobject JSON response $data without echoing it", + async ({ data }) => { + transport.mockResolvedValue(response(data)); + const error = await caughtError(refreshAliyunTokens(PROFILE, REFRESH, deps)); + expect(error.exitCode).toBe(ExitCode.GENERAL); + expect(JSON.stringify(error.toJSON())).not.toContain("fixture-response-secret"); + expectNoSecrets(error); + }, + ); + + test("rejects non-JSON response without echoing HTML or secrets", async () => { + transport.mockResolvedValue(new Response(`${ACCESS} ${REFRESH}`, { status: 502 })); + const error = await caughtError(refreshAliyunTokens(PROFILE, REFRESH, deps)); + expect(error.message).toContain("HTTP 502"); + expectNoSecrets(error); + }); + + test("revoke failure preserves service text and API context, redacting a reflected RT", async () => { + transport.mockResolvedValue( + response( + { + error: "temporarily_unavailable", + error_description: `Service cannot revoke ${REFRESH} yet`, + requestId: "fixture-revoke-request", + }, + 503, + ), + ); + const error = await caughtError(revokeAliyunTokens(PROFILE, REFRESH, deps)); + expect(error.message).toBe("Service cannot revoke [REDACTED] yet"); + expect(error.api).toEqual({ + httpStatus: 503, + apiCode: "temporarily_unavailable", + requestId: "fixture-revoke-request", + }); + expectNoSecrets(error); + }); +}); diff --git a/packages/core/tests/oauth-secure-store.test.ts b/packages/core/tests/oauth-secure-store.test.ts new file mode 100644 index 000000000..a0e94328d --- /dev/null +++ b/packages/core/tests/oauth-secure-store.test.ts @@ -0,0 +1,289 @@ +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { constants, type Stats } from "node:fs"; +import files, { + chmod, + link, + mkdir, + mkdtemp, + readFile, + readdir, + rm, + stat, + symlink, + writeFile, +} from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; +import { createOAuthSecretStore } from "../src/auth/secure-store.ts"; +import { BailianError } from "../src/errors/base.ts"; +import { ExitCode } from "../src/errors/codes.ts"; + +const SESSION = { + refreshToken: "fixture-refresh-secret", + accessToken: "fixture-oauth-secret", + sts: { accessKeySecret: "fixture-sts-secret", securityToken: "fixture-session-secret" }, + consoleTokens: { example: { token: "fixture-console-secret" } }, + unicode: '凭据文件\n"quoted"\\value', +}; +const PAYLOAD = JSON.stringify(SESSION); +const UPDATED = { ...SESSION, refreshToken: "fixture-rotated-refresh-secret" }; +const execFileAsync = promisify(execFile); +const unix = process.platform !== "win32"; + +let configDirectory: string; +beforeEach(async () => { + configDirectory = await mkdtemp(join(tmpdir(), "bl-oauth-store-")); +}); +afterEach(async () => { + vi.restoreAllMocks(); + syncBuiltinESMExports(); + await rm(configDirectory, { recursive: true, force: true }); +}); + +const cacheDirectory = () => join(configDirectory, "oauth"); +const sessionPath = (reference: string) => join(cacheDirectory(), `${reference}.json`); +const fileMode = (status: Stats) => status.mode & 0o777; + +async function expectSafeFailure(operation: Promise, forbidden = SESSION.refreshToken) { + const error: unknown = await operation.then( + () => undefined, + (caught: unknown) => caught, + ); + expect(error).toBeInstanceOf(BailianError); + const failure = error as BailianError; + expect(failure.exitCode).toBe(ExitCode.GENERAL); + expect(failure.message).toMatch(/[\u4e00-\u9fff]/); + expect(failure.hint).toMatch(/[\u4e00-\u9fff]/); + expect(failure.cause).toBeUndefined(); + expect(JSON.stringify(failure.toJSON())).not.toContain(forbidden); +} + +test("writes a private, plaintext session file without touching the main configuration", async () => { + const reference = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + const configPath = join(configDirectory, "config.json"); + await writeFile(configPath, '{"language":"en-US"}', { mode: 0o600 }); + await store.write(reference, PAYLOAD); + expect(await store.read(reference.toUpperCase())).toBe(PAYLOAD); + expect(JSON.parse(await readFile(sessionPath(reference), "utf8"))).toEqual({ + reference, + session: SESSION, + }); + expect(await readFile(configPath, "utf8")).toBe('{"language":"en-US"}'); + expect(await readdir(cacheDirectory())).toEqual([`${reference}.json`]); + if (unix) { + expect(fileMode(await stat(cacheDirectory()))).toBe(0o700); + expect(fileMode(await stat(sessionPath(reference)))).toBe(0o600); + } +}); + +test("reads the same session in a fresh Node process without a credential service", async () => { + const reference = randomUUID(); + await createOAuthSecretStore(configDirectory).write(reference, PAYLOAD); + const modulePath = new URL("../src/auth/secure-store.ts", import.meta.url).href; + // A fresh process verifies persistence without shared memory or putting the payload in argv. + const { stdout, stderr } = await execFileAsync( + process.execPath, + [ + "--import", + "tsx", + "--input-type=module", + "--eval", + `import { createOAuthSecretStore } from ${JSON.stringify(modulePath)}; +const [directory, reference] = process.argv.slice(1); +const session = JSON.parse(await createOAuthSecretStore(directory).read(reference)); +process.stdout.write(String(session.refreshToken === 'fixture-refresh-secret' && session.sts.securityToken === 'fixture-session-secret'));`, + configDirectory, + reference, + ], + { timeout: 12_000, env: { SystemRoot: process.env.SystemRoot, TEMP: configDirectory } }, + ); + expect(stdout).toBe("true"); + expect(stderr).not.toContain(SESSION.refreshToken); +}, 15_000); + +test("missing reads and deletes are not writes", async () => { + const reference = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + expect(await store.read(reference)).toBeUndefined(); + await store.remove(reference); + expect(await readdir(configDirectory)).toEqual([]); +}); + +test.each([ + "../escape", + "/tmp/escape", + "C:\\escape", + "not-a-uuid", + "", + "01234567-89ab-cdef-0123-456789abcdef\n", + "01234567-89ab-cdef-0123-456789abcdef/../escape", + "01234567-89ab-cdef-0123-456789abcdef\\escape", + "01234567-89ab-cdef-0123-456789abcdef\0", + "%2e%2e%2f01234567-89ab-cdef-0123-456789abcdef", +])("rejects unsafe reference %j without side effects", async (reference) => { + const store = createOAuthSecretStore(configDirectory); + await expectSafeFailure(store.read(reference)); + await expectSafeFailure(store.write(reference, PAYLOAD)); + await expectSafeFailure(store.remove(reference)); + expect(await readdir(configDirectory)).toEqual([]); +}); + +test("rejects corrupt or legacy encrypted files without decoding or overwriting them", async () => { + const reference = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + await store.write(reference, PAYLOAD); + const enclosingContents = [ + "not-json", + "null", + "[]", + JSON.stringify({ reference, session: [SESSION] }), + JSON.stringify({ version: 1, algorithm: "aes-256-gcm", ciphertext: "fixture-old-cache" }), + ]; + for (const raw of enclosingContents) { + await writeFile(sessionPath(reference), raw); + await expectSafeFailure(store.read(reference)); + await expectSafeFailure(store.write(reference, PAYLOAD)); + expect(await readFile(sessionPath(reference), "utf8")).toBe(raw); + } + await store.remove(reference); + expect(await store.read(reference)).toBeUndefined(); +}); + +test("rejects a file copied to a different session reference", async () => { + const source = randomUUID(); + const destination = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + await store.write(source, PAYLOAD); + await writeFile(sessionPath(destination), await readFile(sessionPath(source)), { mode: 0o600 }); + await expectSafeFailure(store.read(destination)); + expect(await store.read(source)).toBe(PAYLOAD); +}); + +test("removes only the selected session and is idempotent", async () => { + const removed = randomUUID(); + const retained = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + await store.write(removed, PAYLOAD); + await store.write(retained, PAYLOAD); + await store.remove(removed); + await store.remove(removed); + expect(await store.read(removed)).toBeUndefined(); + expect(await store.read(retained)).toBe(PAYLOAD); + expect(await readdir(cacheDirectory())).toEqual([`${retained}.json`]); +}); + +test.skipIf(!unix)( + "refuses unsafe Unix permissions without relaxing or overwriting files", + async () => { + const reference = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + await chmod(configDirectory, 0o777); + await expectSafeFailure(store.write(reference, PAYLOAD)); + expect(await readdir(configDirectory)).toEqual([]); + await chmod(configDirectory, 0o700); + await mkdir(cacheDirectory(), { mode: 0o755 }); + await chmod(cacheDirectory(), 0o755); + await expectSafeFailure(store.write(reference, PAYLOAD)); + expect(fileMode(await stat(cacheDirectory()))).toBe(0o755); + await chmod(cacheDirectory(), 0o700); + await store.write(reference, PAYLOAD); + await chmod(sessionPath(reference), 0o644); + await expectSafeFailure(store.read(reference)); + await expectSafeFailure(store.write(reference, JSON.stringify(UPDATED))); + await expectSafeFailure(store.remove(reference)); + expect(fileMode(await stat(sessionPath(reference)))).toBe(0o644); + }, +); + +test("refuses a linked cache directory without touching its target", async () => { + const reference = randomUUID(); + const outside = join(configDirectory, "outside"); + await mkdir(outside, { mode: 0o700 }); + await symlink(outside, cacheDirectory(), "junction"); + const store = createOAuthSecretStore(configDirectory); + await expectSafeFailure(store.read(reference)); + await expectSafeFailure(store.write(reference, PAYLOAD)); + await expectSafeFailure(store.remove(reference)); + expect(await readdir(outside)).toEqual([]); +}); + +test.each(unix ? ["symlink", "hardlink"] : ["hardlink"])( + "refuses a %s session file before read, write, or deletion", + async (kind) => { + const reference = randomUUID(); + const outside = join(configDirectory, "outside.json"); + await mkdir(cacheDirectory(), { mode: 0o700 }); + await writeFile(outside, "sentinel", { mode: 0o600 }); + await (kind === "hardlink" ? link : symlink)(outside, sessionPath(reference)); + const store = createOAuthSecretStore(configDirectory); + await expectSafeFailure(store.read(reference)); + await expectSafeFailure(store.write(reference, PAYLOAD)); + await expectSafeFailure(store.remove(reference)); + expect(await readFile(outside, "utf8")).toBe("sentinel"); + expect(await readdir(cacheDirectory())).toEqual([`${reference}.json`]); + }, +); + +test("syncs exclusive private temporaries before rename and rolls back a failed rename", async () => { + const reference = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + const actualOpen = files.open; + const actualRename = files.rename; + const temporaries: string[] = []; + const synced = new Set(); + let failRename = false; + vi.spyOn(files, "open").mockImplementation(async (path, flags, mode) => { + const handle = await actualOpen(path, flags, mode); + if (typeof path === "string" && path.endsWith(".tmp")) { + temporaries.push(path); + expect(Number(flags) & constants.O_EXCL).toBe(constants.O_EXCL); + expect(mode).toBe(0o600); + const actualSync = handle.sync.bind(handle); + vi.spyOn(handle, "sync").mockImplementation(async () => { + if (unix) expect(fileMode(await handle.stat())).toBe(0o600); + expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ + reference, + session: failRename ? UPDATED : SESSION, + }); + await actualSync(); + synced.add(path); + }); + } + return handle; + }); + vi.spyOn(files, "rename").mockImplementation(async (source, destination) => { + expect(synced.delete(String(source))).toBe(true); + if (failRename) throw new Error("fixture-filesystem-secret-error"); + await actualRename(source, destination); + }); + syncBuiltinESMExports(); + await store.write(reference, PAYLOAD); + failRename = true; + await expectSafeFailure( + store.write(reference, JSON.stringify(UPDATED)), + "fixture-filesystem-secret-error", + ); + expect(await store.read(reference)).toBe(PAYLOAD); + expect(new Set(temporaries).size).toBe(2); + expect(await readdir(cacheDirectory())).toEqual([`${reference}.json`]); +}); + +test("replaces the target in one step with a complete new session", async () => { + const reference = randomUUID(); + const store = createOAuthSecretStore(configDirectory); + await store.write(reference, PAYLOAD); + const actualRename = files.rename; + vi.spyOn(files, "rename").mockImplementation(async (source, destination) => { + expect(await store.read(reference)).toBe(PAYLOAD); + await actualRename(source, destination); + expect(await store.read(reference)).toBe(JSON.stringify(UPDATED)); + }); + syncBuiltinESMExports(); + await store.write(reference, JSON.stringify(UPDATED)); + expect(await readdir(cacheDirectory())).toEqual([`${reference}.json`]); +}); diff --git a/packages/core/tests/openapi-provider.test.ts b/packages/core/tests/openapi-provider.test.ts new file mode 100644 index 000000000..abb558bdc --- /dev/null +++ b/packages/core/tests/openapi-provider.test.ts @@ -0,0 +1,1512 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + afterEach, + beforeEach, + describe, + expect, + test, + vi, + type MockInstance, +} from "vite-plus/test"; +import type { AliyunOAuthDeps } from "../src/auth/aliyun-oauth.ts"; +import type { AliyunOAuthProfile, AliyunOAuthSession } from "../src/auth/aliyun-types.ts"; +import { + consoleCredentialKey, + createOpenApiCredentialProvider, + oauthConfigurationFingerprint, +} from "../src/auth/openapi-provider.ts"; +import type { OAuthSecretStore } from "../src/auth/secure-store.ts"; +import { makeAuthStore } from "../src/auth/store.ts"; +import type { ConsoleCredential } from "../src/auth/types.ts"; +import { Client } from "../src/client/client.ts"; +import { httpTransport } from "../src/client/transport.ts"; +import { anonymousConsoleCall } from "../src/console/gateway.ts"; +import { PRE_MODEL_STUDIO_HOST, resolvePreControlPlane } from "../src/config/control-plane.ts"; +import { getConfigPath } from "../src/config/paths.ts"; +import { + activateConfigProfile, + buildSettings, + buildSources, + deleteConfigProfile, + readConfigFile, + readConfigProfiles, + writeConfigFile, + type ResolutionSources, +} from "../src/config/loader.ts"; +import type { ConfigFile } from "../src/config/schema.ts"; +import { BailianError, UsageError } from "../src/errors/base.ts"; +import { CredentialError } from "../src/errors/credential.ts"; +import { enterIsolatedHome, type IsolatedHomeHandle } from "./helpers/isolation.ts"; + +const NOW = Date.UTC(2026, 0, 1); +const REFERENCE = "11111111-1111-4111-8111-111111111111"; +const OTHER_REFERENCE = "22222222-2222-4222-8222-222222222222"; +const ACCESS = "fixture-oauth-access"; +const REFRESH = "fixture-oauth-refresh"; +const ROTATED_ACCESS = "fixture-rotated-access"; +const ROTATED_REFRESH = "fixture-rotated-refresh"; +const MODEL_KEY = "fixture-model-api-key"; +const TARGET: Omit = { + region: "cn-beijing", + site: "domestic", +}; + +function profile(patch: Partial = {}): AliyunOAuthProfile { + return { + client_id: "fixture-native-client", + scope: "openid /internal/bailian/cli", + authorization_url: "https://authorize.example.test/authorize", + oauth_base_url: "https://oauth.example.test", + modelstudio_host: "modelstudio.example.test", + bailiancontrol_host: "bailiancontrol.example.test", + console_gateway: "https://console.example.test", + console_region: "cn-beijing", + session_ref: REFERENCE, + console_enabled: true, + openapi_enabled: true, + ...patch, + }; +} + +function session(patch: Partial = {}): AliyunOAuthSession { + return { + accessToken: ACCESS, + refreshToken: REFRESH, + accessTokenExpiresAt: NOW + 3600_000, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + ...patch, + }; +} + +function sts(expiresAt = NOW + 3600_000): NonNullable { + return { + accessKeyId: "fixture-sts-id", + accessKeySecret: "fixture-sts-secret", + securityToken: "fixture-sts-token", + expiresAt, + }; +} + +function memoryStore() { + const values = new Map(); + const store = { + read: vi.fn(async (reference: string) => values.get(reference)), + write: vi.fn(async (reference: string, raw: string) => { + values.set(reference, raw); + }), + remove: vi.fn(async (reference: string) => { + values.delete(reference); + }), + } satisfies OAuthSecretStore; + const saved = (reference = REFERENCE): AliyunOAuthSession => + JSON.parse(values.get(reference)!) as AliyunOAuthSession; + return { store, values, saved }; +} + +function deferred() { + let resolve!: (value: Value | PromiseLike) => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +function json(data: unknown, status = 200) { + return new Response(JSON.stringify(data), { status }); +} + +function endpointUrl(input: Parameters[0]): string { + expect(typeof input).toBe("string"); + if (typeof input !== "string") throw new Error("OAuth endpoint must be a string"); + return input; +} + +function formBody(init?: RequestInit): URLSearchParams { + expect(typeof init?.body).toBe("string"); + if (typeof init?.body !== "string") throw new Error("OAuth form body must be a string"); + return new URLSearchParams(init.body); +} + +function tokenResponse() { + return json({ + access_token: ROTATED_ACCESS, + refresh_token: ROTATED_REFRESH, + expires_in: 3600, + token_type: "Bearer", + }); +} + +function stsResponse() { + const credential = sts(); + return json({ + accessKeyId: credential.accessKeyId, + accessKeySecret: credential.accessKeySecret, + securityToken: credential.securityToken, + expiration: new Date(credential.expiresAt).toISOString(), + }); +} + +let isolation: IsolatedHomeHandle; +let clock: number; +let deps: AliyunOAuthDeps; +let transport: MockInstance; +beforeEach(() => { + isolation = enterIsolatedHome(); + clock = NOW; + deps = { + identity: { + binName: "fixture-cli", + version: "0.0.0-test", + npmPackage: "fixture-package", + clientName: "fixture-client", + }, + timeout: 5, + now: () => clock, + }; + transport = vi + .spyOn(httpTransport, "fetch") + .mockRejectedValue(new Error("Unexpected OAuth/API request")); +}); +afterEach(() => { + vi.restoreAllMocks(); + isolation.restore(); +}); + +async function setup( + options: { + file?: ConfigFile; + flags?: ResolutionSources["flags"]; + env?: NodeJS.ProcessEnv; + configName?: string; + oauthSession?: AliyunOAuthSession; + } = {}, +) { + const file = options.file ?? { aliyun_oauth: profile() }; + await writeConfigFile({ language: "en-US", ...file }, options.configName); + const sources: ResolutionSources = { + flags: options.flags ?? {}, + env: options.env ?? {}, + file: readConfigFile(options.configName), + configName: options.configName, + configPath: join(isolation.configDir, "config.json"), + }; + const fake = memoryStore(); + if (file.aliyun_oauth) + fake.values.set( + file.aliyun_oauth.session_ref, + JSON.stringify({ + ...(options.oauthSession ?? session()), + configurationFingerprint: oauthConfigurationFingerprint(file.aliyun_oauth), + }), + ); + const storage = { store: fake.store, directory: isolation.configDir }; + return { + ...fake, + sources, + provider: createOpenApiCredentialProvider(sources, deps, storage), + auth: makeAuthStore(sources, deps, storage), + }; +} + +async function configText() { + return readFile(join(isolation.configDir, "config.json"), "utf8"); +} + +function expectNoPlaintextConfig(raw: string) { + const parsed = JSON.parse(raw) as Record; + expect(parsed.access_token).toBeUndefined(); + expect(parsed.access_key_id).toBeUndefined(); + expect(parsed.access_key_secret).toBeUndefined(); + expect(parsed.security_token).toBeUndefined(); + for (const forbidden of [ + ACCESS, + REFRESH, + ROTATED_ACCESS, + ROTATED_REFRESH, + sts().accessKeyId, + sts().accessKeySecret, + sts().securityToken, + "fixture-console-token", + ]) { + expect(raw).not.toContain(forbidden); + } +} + +describe("pre-release control-plane isolation", () => { + test("uses an independent same-name Profile; ignores inherited credentials and validates the file marker", async () => { + const flags = { config: "team" }; + const pre = resolvePreControlPlane({ BAILIAN_PRE: "true" })!; + const onlinePath = getConfigPath(); + await writeConfigFile({ access_key_id: "online-ak", access_key_secret: "online-sk" }, "team"); + process.env.BAILIAN_ACCESS_KEY_ID = "fixture-inherited-ak"; + process.env.BAILIAN_ACCESS_KEY_SECRET = "fixture-inherited-sk"; + process.env.BAILIAN_WORKSPACE_ID = "fixture-online-workspace"; + const sources = buildSources(flags, undefined, pre); + expect(sources.configPath).not.toBe(onlinePath); + expect(sources.file).toEqual({}); + expect(buildSettings(sources).workspaceId).toBeUndefined(); + expect(() => createOpenApiCredentialProvider(sources, deps).assertAvailable()).toThrow( + CredentialError, + ); + const auth = makeAuthStore(sources, deps); + await auth.login({ access_key_id: "pre-ak", access_key_secret: "pre-sk" }); + const preFile = JSON.parse(await readFile(auth.path, "utf8")); + expect(preFile).toMatchObject({ control_environment: "pre", active_config: "team" }); + const markerCopy = join(isolation.configDir, "copied-online.json"); + await writeFile(markerCopy, JSON.stringify(preFile)); + expect(() => readConfigFile("team", markerCopy)).toThrow(/environment/i); + const selected = buildSources({}, undefined, pre); + expect(selected.configName).toBe("team"); + expect(selected.file.access_key_id).toBe("pre-ak"); + expect(buildSources({ config: "default" }, undefined, pre).file.access_key_id).toBeUndefined(); + expect(await auth.logout("all")).toBe(true); + expect(readConfigFile("team", onlinePath).access_key_id).toBe("online-ak"); + expect(transport).not.toHaveBeenCalled(); + }); + + test("routes a static OpenAPI pair to pre-release and refuses unverified services before transport", async () => { + const sources = buildSources( + { accessKeyId: "fixture-pre-ak", accessKeySecret: "fixture-pre-sk" }, + undefined, + {}, + ); + const client = new Client({ + identity: deps.identity, + baseUrl: "https://dashscope.aliyuncs.com", + settings: buildSettings(sources), + openApiProvider: createOpenApiCredentialProvider(sources, deps), + }); + const request = { + host: "modelstudio.cn-beijing.aliyuncs.com", + path: "/readonly", + action: "ListFixture", + version: "2026-01-01", + method: "GET" as const, + }; + await expect( + client.openApiJson({ ...request, host: "other.cn-beijing.aliyuncs.com" }), + ).rejects.toThrow(/pre-release/); + await expect( + anonymousConsoleCall(buildSettings(sources))("fixture.catalog", {}), + ).rejects.toThrow("BAILIAN_PRE_CONSOLE_GATEWAY"); + expect(transport).not.toHaveBeenCalled(); + transport.mockResolvedValueOnce(json({ Success: true })); + await expect(client.openApiJson(request)).resolves.toEqual({ Success: true }); + const [endpoint, init] = transport.mock.calls[0]!; + expect(endpoint).toBe(`https://${PRE_MODEL_STUDIO_HOST}/readonly`); + expect(new Headers(init?.headers).get("authorization")).toContain("Credential=fixture-pre-ak"); + expect(init?.redirect).toBe("error"); + }); +}); + +describe("OpenAPI credential source selection and pure preflight", () => { + const env = { + BAILIAN_ACCESS_KEY_ID: " fixture-bailian-id ", + BAILIAN_ACCESS_KEY_SECRET: " fixture-bailian-secret ", + BAILIAN_SECURITY_TOKEN: " fixture-bailian-token ", + ALIBABA_CLOUD_ACCESS_KEY_ID: "fixture-aliyun-id", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: "fixture-aliyun-secret", + ALIBABA_CLOUD_SECURITY_TOKEN: "fixture-aliyun-token", + }; + test.each([ + { + label: "flag over Bailian env and OAuth", + flags: { + accessKeyId: "fixture-flag-id", + accessKeySecret: "fixture-flag-secret", + securityToken: "fixture-flag-token", + }, + env, + file: { aliyun_oauth: profile() }, + expected: { + accessKeyId: "fixture-flag-id", + accessKeySecret: "fixture-flag-secret", + securityToken: "fixture-flag-token", + source: "flag", + }, + }, + { + label: "Bailian env over OAuth", + env, + file: { aliyun_oauth: profile() }, + expected: { + accessKeyId: "fixture-bailian-id", + accessKeySecret: "fixture-bailian-secret", + securityToken: "fixture-bailian-token", + source: "env", + }, + }, + { + label: "selected static config over Aliyun env", + env: { + ALIBABA_CLOUD_ACCESS_KEY_ID: "fixture-aliyun-id", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: "fixture-aliyun-secret", + ALIBABA_CLOUD_SECURITY_TOKEN: "fixture-aliyun-token", + }, + file: { access_key_id: "fixture-file-id", access_key_secret: "fixture-file-secret" }, + expected: { + accessKeyId: "fixture-file-id", + accessKeySecret: "fixture-file-secret", + securityToken: undefined, + source: "config", + }, + }, + { + label: "Aliyun env when selected file has no credentials", + env: { + ALIBABA_CLOUD_ACCESS_KEY_ID: " fixture-aliyun-id ", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: " fixture-aliyun-secret ", + ALIBABA_CLOUD_SECURITY_TOKEN: "fixture-aliyun-token", + }, + file: {}, + expected: { + accessKeyId: "fixture-aliyun-id", + accessKeySecret: "fixture-aliyun-secret", + securityToken: "fixture-aliyun-token", + source: "env", + }, + }, + ])("$label uses one complete source without secret storage or network", async (fixture) => { + const instance = await setup(fixture); + const before = await configText(); + instance.provider.assertAvailable(); + expect(await instance.provider.getCredential()).toEqual(fixture.expected); + expect(instance.store.read).not.toHaveBeenCalled(); + expect(instance.store.write).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + expect(await configText()).toBe(before); + }); + + test("selected named OAuth profile wins over Aliyun env and stale file AK/SK", async () => { + await writeConfigFile({ + access_key_id: "fixture-default-id", + access_key_secret: "fixture-default-secret", + }); + const instance = await setup({ + configName: "work", + env: { + ALIBABA_CLOUD_ACCESS_KEY_ID: "fixture-env-id", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: "fixture-env-secret", + }, + file: { + aliyun_oauth: profile(), + access_key_id: "fixture-old-id", + access_key_secret: "fixture-old-secret", + }, + oauthSession: session({ sts: sts() }), + }); + expect(await instance.provider.getCredential()).toMatchObject({ + ...sts(), + method: "aliyun-oauth", + sessionRef: REFERENCE, + source: "config", + }); + expect(readConfigFile().access_key_id).toBe("fixture-default-id"); + expect(transport).not.toHaveBeenCalled(); + }); + + test.each([ + { + label: "partial ID flag", + flags: { accessKeyId: "fixture-partial-id" }, + env, + file: { aliyun_oauth: profile() }, + }, + { + label: "partial secret flag", + flags: { accessKeySecret: "fixture-partial-secret" }, + env, + file: { aliyun_oauth: profile() }, + }, + { + label: "explicit blank flag", + flags: { accessKeyId: " " }, + env, + file: { aliyun_oauth: profile() }, + }, + { + label: "partial Bailian ID env", + env: { + BAILIAN_ACCESS_KEY_ID: "fixture-partial-id", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: "fixture-other-secret", + }, + file: { aliyun_oauth: profile() }, + }, + { + label: "partial Bailian secret env", + env: { BAILIAN_ACCESS_KEY_SECRET: "fixture-partial-secret" }, + file: { access_key_id: "fixture-file-id", access_key_secret: "fixture-file-secret" }, + }, + { + label: "partial file pair", + env: { + ALIBABA_CLOUD_ACCESS_KEY_ID: "fixture-env-id", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: "fixture-env-secret", + }, + file: { access_key_id: "fixture-file-id" }, + }, + { + label: "partial Aliyun env", + env: { ALIBABA_CLOUD_ACCESS_KEY_ID: "fixture-partial-id" }, + file: {}, + }, + ])("$label never borrows the missing half from another source", async (fixture) => { + const instance = await setup(fixture); + expect(() => instance.provider.assertAvailable()).toThrow(CredentialError); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(instance.store.read).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + }); + + test("security token alone does not select a source or leak into a lower-priority pair", async () => { + const instance = await setup({ + file: {}, + flags: { securityToken: "fixture-unpaired-flag-token" }, + env: { + BAILIAN_SECURITY_TOKEN: "fixture-unpaired-bailian-token", + ALIBABA_CLOUD_ACCESS_KEY_ID: "fixture-aliyun-id", + ALIBABA_CLOUD_ACCESS_KEY_SECRET: "fixture-aliyun-secret", + }, + }); + expect(await instance.provider.getCredential()).toEqual({ + accessKeyId: "fixture-aliyun-id", + accessKeySecret: "fixture-aliyun-secret", + securityToken: undefined, + source: "env", + }); + }); + + test("assert/describe/stored/static dry-run inspect metadata only, even with a missing secret", async () => { + const instance = await setup({ + file: { aliyun_oauth: profile(), api_key: MODEL_KEY }, + flags: { dryRun: true }, + }); + instance.values.clear(); + const before = await configText(); + instance.provider.assertAvailable(); + instance.provider.assertAvailable("console"); + expect(instance.auth.describe()).toMatchObject({ + aliyunOAuth: profile(), + apiKey: { token: MODEL_KEY }, + }); + expect(instance.auth.stored()).toMatchObject({ + aliyunOAuth: true, + console: true, + openapi: true, + apiKey: true, + }); + expect(buildSettings(instance.sources).dryRun).toBe(true); + expect(instance.provider.resolveConsoleTarget(TARGET)).toEqual({ + ...TARGET, + gateway: profile().console_gateway, + }); + expect(instance.store.read).not.toHaveBeenCalled(); + expect(instance.store.write).not.toHaveBeenCalled(); + expect(instance.store.remove).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + expect(await configText()).toBe(before); + }); + + test("absent named profile never falls back to the default profile's secrets", async () => { + await writeConfigFile({ aliyun_oauth: profile(), api_key: MODEL_KEY }); + const instance = await setup({ configName: "empty", file: {} }); + expect(() => instance.provider.assertAvailable()).toThrow(CredentialError); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(instance.store.read).not.toHaveBeenCalled(); + }); +}); + +describe("OAuth STS lifecycle, durable rotation and single-flight", () => { + test("valid STS is reused across calls and provider recreation without refreshing expired AT", async () => { + const instance = await setup({ + oauthSession: session({ accessTokenExpiresAt: NOW - 1, sts: sts() }), + }); + const before = await configText(); + const first = await instance.provider.getCredential(); + expect(await instance.provider.getCredential("console")).toEqual(first); + const recreated = createOpenApiCredentialProvider(instance.sources, deps, { + store: instance.store, + directory: isolation.configDir, + }); + expect(await recreated.getCredential()).toEqual(first); + expect(instance.store.read).toHaveBeenCalledTimes(2); + expect(instance.store.write).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + expect(await configText()).toBe(before); + }); + + test.each([30_001, 30_000, 29_999])( + "STS expiry margin %i ms has a strict 30-second boundary", + async (remaining) => { + const instance = await setup({ oauthSession: session({ sts: sts(NOW + remaining) }) }); + transport.mockImplementation(async () => stsResponse()); + await instance.provider.getCredential(); + expect(transport).toHaveBeenCalledTimes(remaining > 30_000 ? 0 : 1); + if (remaining <= 30_000) + expect(endpointUrl(transport.mock.calls[0]![0])).toMatch(/\/v1\/exchange$/); + }, + ); + + test("valid AT exchanges STS only and writes expiry metadata, never plaintext credentials", async () => { + const instance = await setup(); + transport.mockResolvedValue(stsResponse()); + expect(await instance.provider.getCredential()).toMatchObject({ + ...sts(), + method: "aliyun-oauth", + }); + expect(transport).toHaveBeenCalledTimes(1); + const [endpoint, init] = transport.mock.calls[0]!; + expect(endpointUrl(endpoint)).toBe(`${profile().oauth_base_url}/v1/exchange`); + expect(new Headers(init?.headers).get("authorization")).toBe(`Bearer ${ACCESS}`); + expect(instance.saved()).toMatchObject({ refreshToken: REFRESH, sts: sts() }); + expect(readConfigFile().aliyun_oauth).toMatchObject({ + access_token_expires_at: NOW + 3600_000, + sts_expires_at: sts().expiresAt, + }); + expectNoPlaintextConfig(await configText()); + }); + + test.each([30_001, 30_000, 0, -1])( + "AT expiry margin %i ms refreshes only when needed before STS", + async (remaining) => { + const instance = await setup({ + oauthSession: session({ accessTokenExpiresAt: NOW + remaining }), + }); + transport.mockImplementation(async (endpoint) => + endpointUrl(endpoint).endsWith("/v1/token") ? tokenResponse() : stsResponse(), + ); + await instance.provider.getCredential(); + expect( + transport.mock.calls.map(([endpoint]) => new URL(endpointUrl(endpoint)).pathname), + ).toEqual(remaining > 30_000 ? ["/v1/exchange"] : ["/v1/token", "/v1/exchange"]); + expect(instance.saved().refreshToken).toBe(remaining > 30_000 ? REFRESH : ROTATED_REFRESH); + expect(instance.saved().refreshPending).not.toBe(true); + expectNoPlaintextConfig(await configText()); + }, + ); + + test("in-memory cache expires against injected now and refreshes STS without sleeping", async () => { + const instance = await setup({ + oauthSession: session({ accessTokenExpiresAt: NOW + 7200_000, sts: sts() }), + }); + await instance.provider.getCredential(); + clock = NOW + 3600_000 - 30_000; + transport.mockResolvedValue( + json({ + accessKeyId: sts().accessKeyId, + accessKeySecret: sts().accessKeySecret, + securityToken: sts().securityToken, + expiration: new Date(clock + 3600_000).toISOString(), + }), + ); + await instance.provider.getCredential(); + expect(transport).toHaveBeenCalledTimes(1); + expect(instance.saved().sts?.expiresAt).toBe(clock + 3600_000); + }); + + test("parallel callers share one refresh/exchange and keep a rotated RT durable before STS", async () => { + const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); + const refreshEntered = deferred(); + const allowRefresh = deferred(); + transport.mockImplementation(async (endpoint, init) => { + if (endpointUrl(endpoint).endsWith("/v1/token")) { + expect(instance.saved().refreshPending).toBe(true); + expect(formBody(init).get("refresh_token")).toBe(REFRESH); + refreshEntered.resolve(); + await allowRefresh.promise; + return tokenResponse(); + } + expect(instance.saved()).toMatchObject({ + refreshToken: ROTATED_REFRESH, + refreshPending: false, + accessToken: ROTATED_ACCESS, + }); + return stsResponse(); + }); + const calls = [ + instance.provider.getCredential(), + instance.provider.getCredential("console"), + instance.provider.getCredential(), + ]; + try { + await refreshEntered.promise; + } finally { + allowRefresh.resolve(); + } + const credentials = await Promise.all(calls); + expect(credentials).toEqual([credentials[0], credentials[0], credentials[0]]); + expect( + transport.mock.calls.map(([endpoint]) => new URL(endpointUrl(endpoint)).pathname), + ).toEqual(["/v1/token", "/v1/exchange"]); + expect(instance.store.read).toHaveBeenCalledTimes(1); + expect(instance.store.write).toHaveBeenCalledTimes(3); + }); + + test("rotated RT survives a dependent STS business failure and provider recreation never replays old RT", async () => { + const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); + transport.mockImplementation(async (endpoint) => { + if (endpointUrl(endpoint).endsWith("/v1/token")) return tokenResponse(); + expect(instance.saved().refreshToken).toBe(ROTATED_REFRESH); + return json( + { + error: "fixture_business_error", + error_description: "STS unavailable verbatim", + requestId: "fixture-sts-request", + }, + 503, + ); + }); + await expect(instance.provider.getCredential()).rejects.toMatchObject({ + message: "STS unavailable verbatim", + api: { httpStatus: 503, apiCode: "fixture_business_error", requestId: "fixture-sts-request" }, + }); + expect(instance.saved()).toMatchObject({ + refreshToken: ROTATED_REFRESH, + refreshPending: false, + }); + const recreated = createOpenApiCredentialProvider(instance.sources, deps, { + store: instance.store, + directory: isolation.configDir, + }); + transport.mockClear().mockResolvedValue(stsResponse()); + await recreated.getCredential(); + expect(transport).toHaveBeenCalledTimes(1); + expect(endpointUrl(transport.mock.calls[0]![0])).toMatch(/\/v1\/exchange$/); + expect(new Headers(transport.mock.calls[0]![1]?.headers).get("authorization")).toBe( + `Bearer ${ROTATED_ACCESS}`, + ); + }); + + test("refresh failure leaves a durable pending marker; same and new providers refuse RT replay", async () => { + const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); + const recoveryDeps = { ...deps, recoveryHint: "fixture-recovery-hint" }; + const provider = createOpenApiCredentialProvider(instance.sources, recoveryDeps, { + store: instance.store, + directory: isolation.configDir, + }); + transport.mockResolvedValue( + json( + { + error: "invalid_grant", + error_description: "Refresh rejected verbatim", + requestId: "fixture-refresh-request", + }, + 400, + ), + ); + await expect(provider.getCredential()).rejects.toMatchObject({ + message: "Refresh rejected verbatim", + hint: "fixture-recovery-hint", + api: { httpStatus: 400, apiCode: "invalid_grant", requestId: "fixture-refresh-request" }, + }); + expect(instance.saved().refreshPending).toBe(true); + await expect(provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + const recreated = createOpenApiCredentialProvider(instance.sources, deps, { + store: instance.store, + directory: isolation.configDir, + }); + await expect(recreated.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(transport).toHaveBeenCalledTimes(1); + }); + + test("failure to save rotated RT blocks business requests and leaves old RT marked unsafe", async () => { + const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); + const write = instance.store.write.getMockImplementation()!; + instance.store.write.mockImplementation(async (reference, raw) => { + if ((JSON.parse(raw) as AliyunOAuthSession).refreshToken === ROTATED_REFRESH) + throw new Error("fixture-storage-failed"); + await write(reference, raw); + }); + transport.mockResolvedValue(tokenResponse()); + await expect(instance.provider.getCredential()).rejects.toThrow("fixture-storage-failed"); + expect(instance.saved()).toMatchObject({ refreshToken: REFRESH, refreshPending: true }); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + const recreated = createOpenApiCredentialProvider(instance.sources, deps, { + store: instance.store, + directory: isolation.configDir, + }); + await expect(recreated.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(transport).toHaveBeenCalledTimes(1); + expect(endpointUrl(transport.mock.calls[0]![0])).toMatch(/\/v1\/token$/); + }); + + test("failure to save pending marker sends no refresh or business request", async () => { + const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); + instance.store.write.mockRejectedValue(new Error("fixture-pending-save-failed")); + await expect(instance.provider.getCredential()).rejects.toThrow("fixture-pending-save-failed"); + expect(instance.saved().refreshPending).toBeUndefined(); + expect(transport).not.toHaveBeenCalled(); + }); + + test("preexisting pending state rejects even otherwise-valid STS", async () => { + const instance = await setup({ oauthSession: session({ refreshPending: true, sts: sts() }) }); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(instance.store.write).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + }); + + test.each( + [ + undefined, + "not-json", + "null", + "[]", + "{}", + JSON.stringify(session({ accessTokenExpiresAt: Infinity })), + JSON.stringify(session({ sts: { ...sts(), securityToken: "" } })), + ].map((raw) => ({ raw })), + )("missing or corrupt opaque session $raw fails before requests", async ({ raw }) => { + const instance = await setup(); + if (raw === undefined) instance.values.clear(); + else instance.values.set(REFERENCE, raw); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(transport).not.toHaveBeenCalled(); + expect(instance.store.write).not.toHaveBeenCalled(); + }); +}); + +describe("Console cache and endpoint isolation", () => { + test("Console tokens are scoped by switchAgent and gateway and survive provider recreation only in opaque storage", async () => { + const instance = await setup(); + const target = instance.provider.resolveConsoleTarget(TARGET); + const credential: ConsoleCredential = { + ...target, + token: "fixture-console-token", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + expiresAt: NOW + 3600_000, + source: "config", + }; + await instance.provider.saveConsoleCredential(credential); + await instance.provider.saveConsoleCredential({ + ...credential, + token: "fixture-agent-console-token", + switchAgent: 7, + }); + expect(await instance.provider.getConsoleCredential(TARGET)).toEqual(credential); + expect( + await instance.provider.getConsoleCredential({ ...TARGET, switchAgent: 7 }), + ).toMatchObject({ token: "fixture-agent-console-token" }); + expect( + await instance.provider.getConsoleCredential({ ...TARGET, switchAgent: 8 }), + ).toBeUndefined(); + const recreated = createOpenApiCredentialProvider(instance.sources, deps, { + store: instance.store, + directory: isolation.configDir, + }); + expect(await recreated.getConsoleCredential(TARGET)).toEqual(credential); + expect(Object.keys(instance.saved().consoleTokens!)).toHaveLength(2); + expect(transport).not.toHaveBeenCalled(); + expectNoPlaintextConfig(await configText()); + }); + + test.each([ + { ...TARGET, region: "cn-shanghai" }, + { ...TARGET, site: "international" as const }, + { ...TARGET, gateway: "https://different-console.example.test" }, + ])("rejects mismatched Console target %j without reading secrets", async (target) => { + const instance = await setup(); + expect(() => instance.provider.resolveConsoleTarget(target)).toThrow(UsageError); + await expect(instance.provider.getConsoleCredential(target)).rejects.toBeInstanceOf(UsageError); + await expect( + instance.provider.saveConsoleCredential({ + ...target, + token: "fixture-console-token", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }), + ).rejects.toBeInstanceOf(UsageError); + expect(instance.store.read).not.toHaveBeenCalled(); + expect(instance.store.write).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + }); + + test("cache keys distinguish gateway, region, site and switchAgent including zero", () => { + const targets = [ + TARGET, + { ...TARGET, gateway: profile().console_gateway }, + { ...TARGET, region: "cn-shanghai" }, + { ...TARGET, site: "international" as const }, + { ...TARGET, switchAgent: 0 }, + { ...TARGET, switchAgent: 1 }, + ]; + expect(new Set(targets.map(consoleCredentialKey)).size).toBe(targets.length); + }); + + test("changing explicit gateway on the same session cannot reuse tokens from the old gateway", async () => { + const instance = await setup(); + await instance.provider.saveConsoleCredential({ + ...TARGET, + token: "fixture-console-token", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }); + await writeConfigFile({ + aliyun_oauth: profile({ console_gateway: "https://other-console.example.test" }), + }); + await expect(instance.provider.getConsoleCredential(TARGET)).rejects.toBeInstanceOf( + CredentialError, + ); + expect(instance.provider.resolveConsoleTarget(TARGET).gateway).toBe( + "https://other-console.example.test", + ); + }); + + test.each([30_001, 30_000, 0])( + "Console cached expiry %i ms returns only a valid token and never writes plaintext", + async (remaining) => { + const instance = await setup(); + await instance.provider.saveConsoleCredential({ + ...TARGET, + token: "fixture-console-token", + expiresAt: NOW + remaining, + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }); + const before = await configText(); + const credential = await instance.provider.getConsoleCredential(TARGET); + expect(credential?.token).toBe(remaining > 30_000 ? "fixture-console-token" : undefined); + expect(await configText()).toBe(before); + expectNoPlaintextConfig(before); + expect(transport).not.toHaveBeenCalled(); + }, + ); + + test("unexpired Console token becomes unavailable when injected time enters safety margin", async () => { + const instance = await setup(); + await instance.provider.saveConsoleCredential({ + ...TARGET, + token: "fixture-console-token", + expiresAt: NOW + 60_000, + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }); + expect(await instance.provider.getConsoleCredential(TARGET)).toBeDefined(); + clock += 30_000; + expect(await instance.provider.getConsoleCredential(TARGET)).toBeUndefined(); + expectNoPlaintextConfig(await configText()); + }); + + test("separate providers merge Console cache writes under the real session lock", async () => { + const instance = await setup(); + const second = createOpenApiCredentialProvider(instance.sources, deps, { + store: instance.store, + directory: isolation.configDir, + }); + await Promise.all([ + instance.provider.saveConsoleCredential({ + ...TARGET, + token: "fixture-console-token", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }), + second.saveConsoleCredential({ + ...TARGET, + switchAgent: 7, + token: "fixture-agent-token", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }), + ]); + expect(Object.keys(instance.saved().consoleTokens!)).toHaveLength(2); + }); + + test("temporary static credentials and their derived Console token never persist into OAuth storage", async () => { + const instance = await setup({ + file: {}, + env: { + BAILIAN_ACCESS_KEY_ID: "fixture-temp-id", + BAILIAN_ACCESS_KEY_SECRET: "fixture-temp-secret", + BAILIAN_SECURITY_TOKEN: "fixture-temp-token", + }, + }); + const before = await configText(); + await instance.provider.getCredential("console"); + await instance.provider.saveConsoleCredential({ + ...TARGET, + token: "fixture-console-token", + source: "env", + }); + expect(await instance.provider.getConsoleCredential(TARGET)).toBeUndefined(); + expect(instance.store.read).not.toHaveBeenCalled(); + expect(instance.store.write).not.toHaveBeenCalled(); + expect(await configText()).toBe(before); + }); + + test("routes ModelStudio/BailianControl only to explicit profile hosts, leaving unknown hosts alone", async () => { + const instance = await setup({ oauthSession: session({ sts: sts() }) }); + const credential = await instance.provider.getCredential(); + expect(instance.provider.resolveHost("modelstudio.aliyuncs.com", credential)).toBe( + profile().modelstudio_host, + ); + expect( + instance.provider.resolveHost("modelstudio.cn-beijing.aliyuncs.com", credential, "console"), + ).toBe(profile().modelstudio_host); + expect(instance.provider.resolveHost("bailiancontrol.aliyuncs.com", credential)).toBe( + profile().bailiancontrol_host, + ); + expect( + instance.provider.resolveHost("bailiancontrol.cn-beijing.aliyuncs.com", credential), + ).toBe(profile().bailiancontrol_host); + expect(instance.provider.resolveHost("unknown.example.test", credential)).toBe( + "unknown.example.test", + ); + }); + + test("BailianControl without an explicit host fails locally instead of guessing endpoints", async () => { + const instance = await setup({ + file: { aliyun_oauth: profile({ bailiancontrol_host: undefined }) }, + }); + expect(() => instance.provider.resolveHost("bailiancontrol.aliyuncs.com")).toThrow(UsageError); + expect(transport).not.toHaveBeenCalled(); + }); +}); + +describe("Profile references, login and domain-specific logout", () => { + test("the default file store survives new providers, persists rotated tokens and removes only the session on logout", async () => { + const configPath = join(isolation.configDir, "config.json"); + const sources: ResolutionSources = { flags: {}, env: {}, file: {}, configPath }; + const auth = makeAuthStore(sources, deps); + await writeConfigFile({ api_key: MODEL_KEY }); + await auth.loginAliyun(profile(), session({ accessTokenExpiresAt: NOW, sts: sts(NOW) })); + + const file = readConfigFile(undefined, configPath); + const metadata = file.aliyun_oauth!; + const sessionPath = join(isolation.configDir, "oauth", `${metadata.session_ref}.json`); + expect(JSON.parse(await readFile(sessionPath, "utf8"))).toMatchObject({ + reference: metadata.session_ref, + session: { accessToken: ACCESS, refreshToken: REFRESH }, + }); + expectNoPlaintextConfig(await configText()); + const provider = createOpenApiCredentialProvider({ ...sources, file }, deps); + transport + .mockResolvedValueOnce(tokenResponse()) + .mockResolvedValueOnce(stsResponse()) + .mockResolvedValueOnce(new Response(null, { status: 204 })); + expect(await provider.getCredential()).toMatchObject({ + method: "aliyun-oauth", + expiresAt: NOW + 3600_000, + }); + expect(JSON.parse(await readFile(sessionPath, "utf8"))).toMatchObject({ + session: { refreshToken: ROTATED_REFRESH, refreshPending: false }, + }); + expectNoPlaintextConfig(await configText()); + expect(await makeAuthStore(sources, deps).logout("aliyun")).toBe(true); + expect(transport.mock.calls.map(([input]) => new URL(endpointUrl(input)).pathname)).toEqual([ + "/v1/token", + "/v1/exchange", + "/v1/revoke", + ]); + expect(formBody(transport.mock.calls[2]?.[1]).get("token")).toBe(ROTATED_REFRESH); + await expect(readFile(sessionPath, "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + expect(readConfigFile()).toEqual({ + api_key: MODEL_KEY, + console_region: "cn-beijing", + console_site: "domestic", + }); + }); + + test("named login stores only metadata, activates selected profile and preserves model key and other profiles", async () => { + await writeConfigFile({ api_key: MODEL_KEY }); + const instance = await setup({ file: {}, configName: "work", flags: { config: "work" } }); + await instance.auth.loginAliyun(profile(), session({ sts: sts() })); + const named = readConfigFile("work").aliyun_oauth!; + expect(named.session_ref).toMatch( + /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/, + ); + expect(named.session_ref).not.toBe(REFERENCE); + expect(instance.values.get(named.session_ref)).toBe(JSON.stringify(session({ sts: sts() }))); + expect(readConfigProfiles().active).toBe("work"); + expect(readConfigFile().api_key).toBe(MODEL_KEY); + expect(readConfigFile("work")).toMatchObject({ + console_region: "cn-beijing", + console_site: "domestic", + }); + expectNoPlaintextConfig(await configText()); + }); + + test("secure login write failure leaves previous metadata and session untouched", async () => { + const instance = await setup(); + const before = await configText(); + instance.store.write.mockRejectedValue(new Error("fixture-login-storage-failed")); + await expect(instance.auth.loginAliyun(profile(), session())).rejects.toThrow( + "fixture-login-storage-failed", + ); + expect(await configText()).toBe(before); + expect(instance.saved()).toEqual(session()); + expect(instance.store.remove).not.toHaveBeenCalled(); + }); + + test("relogin uses a new reference and invalidates credentials held by the old provider", async () => { + const instance = await setup({ oauthSession: session({ sts: sts() }) }); + const previous = await instance.provider.getCredential(); + await instance.auth.loginAliyun( + profile(), + session({ + accessToken: ROTATED_ACCESS, + refreshToken: ROTATED_REFRESH, + sts: { ...sts(), accessKeyId: "fixture-new-sts-id" }, + }), + ); + const nextReference = readConfigFile().aliyun_oauth!.session_ref; + expect(nextReference).not.toBe(REFERENCE); + expect(instance.values.has(REFERENCE)).toBe(false); + expect(() => instance.provider.resolveHost("modelstudio.aliyuncs.com", previous)).toThrow( + CredentialError, + ); + const next = await instance.provider.getCredential(); + expect(next.sessionRef).toBe(nextReference); + expect(next.accessKeyId).toBe("fixture-new-sts-id"); + expect(transport).not.toHaveBeenCalled(); + }); + + test("provider is pinned to its selected profile even when active profile changes", async () => { + const instance = await setup({ configName: "first", oauthSession: session({ sts: sts() }) }); + await writeConfigFile({ aliyun_oauth: profile({ session_ref: OTHER_REFERENCE }) }, "second"); + instance.values.set( + OTHER_REFERENCE, + JSON.stringify(session({ sts: { ...sts(), accessKeyId: "fixture-other-profile-id" } })), + ); + await activateConfigProfile("second"); + expect((await instance.provider.getCredential()).sessionRef).toBe(REFERENCE); + await expect(deleteConfigProfile("first")).rejects.toThrow(/OAuth/); + transport.mockResolvedValueOnce(new Response(null, { status: 200 })); + await instance.auth.logout("aliyun"); + await deleteConfigProfile("first"); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(readConfigFile("first").aliyun_oauth).toBeUndefined(); + }); + + test("reference removal during an exchange never restores old metadata or returns old credentials", async () => { + const instance = await setup(); + const exchangeEntered = deferred(); + const allowExchange = deferred(); + transport.mockImplementation(async () => { + exchangeEntered.resolve(); + await allowExchange.promise; + return stsResponse(); + }); + const outcome = instance.provider.getCredential().then( + () => undefined, + (error: unknown) => error, + ); + try { + await exchangeEntered.promise; + await writeConfigFile({ api_key: MODEL_KEY }); + } finally { + allowExchange.resolve(); + } + expect(await outcome).toBeInstanceOf(CredentialError); + expect(readConfigFile().aliyun_oauth).toBeUndefined(); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(readConfigFile().api_key).toBe(MODEL_KEY); + }); + + test("failed revoke preserves retryable local state; successful OAuth logout preserves model API key", async () => { + const instance = await setup({ + file: { aliyun_oauth: profile(), api_key: MODEL_KEY, base_url: "https://model.example.test" }, + oauthSession: session({ sts: sts() }), + }); + const credential = await instance.provider.getCredential(); + const before = await configText(); + const secretBefore = instance.values.get(REFERENCE); + transport.mockResolvedValue( + json({ error: "temporarily_unavailable", error_description: "fixture-revoke-error" }, 503), + ); + await expect(instance.auth.logout("aliyun")).rejects.toBeInstanceOf(BailianError); + expect(await configText()).toBe(before); + expect(instance.values.get(REFERENCE)).toBe(secretBefore); + expect(instance.store.remove).not.toHaveBeenCalled(); + transport.mockResolvedValue(new Response(null, { status: 204 })); + expect(await instance.auth.logout("aliyun")).toBe(true); + expect(readConfigFile()).toMatchObject({ + api_key: MODEL_KEY, + base_url: "https://model.example.test", + }); + expect(readConfigFile().aliyun_oauth).toBeUndefined(); + expect(instance.values.has(REFERENCE)).toBe(false); + expect(() => instance.provider.resolveHost("modelstudio.aliyuncs.com", credential)).toThrow( + CredentialError, + ); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + expect(await instance.auth.logout("aliyun")).toBe(false); + expect(transport).toHaveBeenCalledTimes(2); + }); + + test.each(["console", "openapi"] as const)( + "%s logout disables only its own OAuth domain and does not revoke shared RT", + async (scope) => { + const cacheKey = consoleCredentialKey({ ...TARGET, gateway: profile().console_gateway }); + const instance = await setup({ + file: { + aliyun_oauth: profile(), + api_key: MODEL_KEY, + access_token: "fixture-static-console", + access_key_id: "fixture-static-id", + access_key_secret: "fixture-static-secret", + security_token: "fixture-static-token", + }, + oauthSession: session({ + sts: sts(), + consoleTokens: { + [cacheKey]: { token: "fixture-console-token", expiresAt: NOW + 3600_000 }, + }, + }), + }); + await instance.provider.getCredential(); + expect(await instance.auth.logout(scope)).toBe(true); + expect(readConfigFile().aliyun_oauth).toMatchObject({ + session_ref: REFERENCE, + console_enabled: scope !== "console", + openapi_enabled: scope !== "openapi", + }); + expect(readConfigFile().api_key).toBe(MODEL_KEY); + expect(instance.saved().refreshToken).toBe(REFRESH); + expect(instance.store.remove).not.toHaveBeenCalled(); + if (scope === "console") { + expect(readConfigFile().access_token).toBeUndefined(); + expect(instance.saved().consoleTokens).toEqual({}); + expect(await instance.provider.getConsoleCredential(TARGET)).toBeUndefined(); + expect((await instance.provider.getCredential()).method).toBe("aliyun-oauth"); + } else { + expect(readConfigFile().access_key_id).toBeUndefined(); + expect(readConfigFile().access_key_secret).toBeUndefined(); + expect(readConfigFile().security_token).toBeUndefined(); + expect((await instance.provider.getCredential("console")).method).toBe("aliyun-oauth"); + expect((await instance.provider.getConsoleCredential(TARGET))?.token).toBe( + "fixture-console-token", + ); + await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); + } + expect(transport).not.toHaveBeenCalled(); + }, + ); + + test.each(["console", "openapi"] as const)( + "static %s login disables only the replaced OAuth domain", + async (domain) => { + const instance = await setup({ oauthSession: session({ sts: sts() }) }); + await instance.auth.login( + domain === "console" + ? { access_token: "fixture-static-console" } + : { access_key_id: "fixture-static-id", access_key_secret: "fixture-static-secret" }, + ); + expect(readConfigFile().aliyun_oauth).toMatchObject({ + console_enabled: domain !== "console", + openapi_enabled: domain !== "openapi", + session_ref: REFERENCE, + }); + expect(instance.values.has(REFERENCE)).toBe(true); + expect(instance.store.remove).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + }, + ); + + test("all logout clears every credential, while preserving unrelated settings and other profiles", async () => { + const instance = await setup({ + file: { + aliyun_oauth: profile(), + api_key: MODEL_KEY, + base_url: "https://model.example.test", + access_token: "fixture-static-console", + access_key_id: "fixture-static-id", + access_key_secret: "fixture-static-secret", + security_token: "fixture-static-token", + workspace_id: "fixture-workspace", + output: "json", + }, + }); + await writeConfigFile({ api_key: "fixture-other-model-key" }, "other"); + transport.mockResolvedValue(new Response(null, { status: 204 })); + expect(await instance.auth.logout("all")).toBe(true); + const file = readConfigFile(); + for (const field of [ + "api_key", + "base_url", + "aliyun_oauth", + "access_token", + "access_key_id", + "access_key_secret", + "security_token", + ] as const) + expect(file[field]).toBeUndefined(); + expect(file).toMatchObject({ workspace_id: "fixture-workspace", output: "json" }); + expect(readConfigFile("other").api_key).toBe("fixture-other-model-key"); + expect(instance.values.size).toBe(0); + expect(await instance.auth.logout("all")).toBe(false); + expect(transport).toHaveBeenCalledTimes(1); + }); +}); + +interface FixtureChild { + process: ChildProcess; + completion: Promise<{ code: number | null; stdout: string; stderr: string }>; + contended: Promise; +} + +function startLockContender(sources: ResolutionSources, fakeFile: string): FixtureChild { + const providerUrl = new URL("../src/auth/openapi-provider.ts", import.meta.url).href; + const transportUrl = new URL("../src/client/transport.ts", import.meta.url).href; + const loaderUrl = new URL("../src/config/loader.ts", import.meta.url).href; + const script = ` + import files from 'node:fs/promises'; + import { syncBuiltinESMExports } from 'node:module'; + import { createOpenApiCredentialProvider, oauthSessionLockPath } from ${JSON.stringify(providerUrl)}; + import { httpTransport } from ${JSON.stringify(transportUrl)}; + import { readConfigFile } from ${JSON.stringify(loaderUrl)}; + const sources = ${JSON.stringify(sources)}; + sources.file = readConfigFile(sources.configName); + const directory = ${JSON.stringify(isolation.configDir)}; + const fakeFile = ${JSON.stringify(fakeFile)}; + const lockPath = oauthSessionLockPath(directory, sources.file.aliyun_oauth.session_ref); + const actualOpen = files.open; + files.open = async (...args) => { + try { return await actualOpen(...args); } + catch (error) { + if (String(args[0]) === lockPath && error.code === 'EEXIST') process.send({ type: 'contended' }); + throw error; + } + }; + syncBuiltinESMExports(); + httpTransport.fetch = async () => { throw new Error('A second process must reuse durable STS, not replay RT'); }; + const store = { + read: async () => files.readFile(fakeFile, 'utf8'), + write: async () => { throw new Error('A second process must not overwrite this fixture session'); }, + remove: async () => { throw new Error('Unexpected removal'); }, + }; + const provider = createOpenApiCredentialProvider(sources, { + identity: ${JSON.stringify(deps.identity)}, timeout: 5, now: () => ${NOW}, + }, { store, directory }); + const credential = await provider.getCredential(); + process.stdout.write(JSON.stringify({ accessKeyId: credential.accessKeyId, sessionRef: credential.sessionRef })); + process.disconnect(); + `; + const child = spawn( + process.execPath, + ["--import", "tsx", "--input-type=module", "--eval", script], + { + cwd: fileURLToPath(new URL("../../../", import.meta.url)), + // Explicit environment: never inherit HOME credentials, proxy or NODE_OPTIONS/preload. + env: { + PATH: process.env.PATH, + HOME: isolation.home, + USERPROFILE: isolation.home, + XDG_CONFIG_HOME: join(isolation.home, ".config"), + BAILIAN_CONFIG_DIR: isolation.configDir, + BL_SKIP_HOST_AGENTS: "1", + DO_NOT_TRACK: "1", + }, + stdio: ["ignore", "pipe", "pipe", "ipc"], + }, + ); + const deadline = setTimeout(() => child.kill(), 10_000); + child.once("close", () => clearTimeout(deadline)); + child.once("error", () => clearTimeout(deadline)); + let stdout = ""; + let stderr = ""; + child.stdout!.on("data", (chunk: Buffer) => { + stdout += chunk.toString(); + }); + child.stderr!.on("data", (chunk: Buffer) => { + stderr += chunk.toString(); + }); + const completion = new Promise<{ code: number | null; stdout: string; stderr: string }>( + (resolveCompletion, rejectCompletion) => { + child.once("error", rejectCompletion); + child.once("close", (code) => resolveCompletion({ code, stdout, stderr })); + }, + ); + const contended = new Promise((resolveContention, rejectContention) => { + child.on("message", (message: unknown) => { + if ((message as { type?: string }).type === "contended") resolveContention(); + }); + child.once("error", rejectContention); + child.once("close", () => + rejectContention(new Error(`Child closed before lock contention: ${stderr}`)), + ); + }); + return { process: child, completion, contended }; +} + +describe("OAuth credential binding regressions", () => { + test("a late Console token cannot overwrite a newly signed-in session", async () => { + const instance = await setup({ oauthSession: session({ sts: sts() }) }); + const oldCredential: ConsoleCredential = { + ...TARGET, + gateway: profile().console_gateway, + token: "old-console", + source: "config", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + }; + await instance.auth.loginAliyun( + profile(), + session({ + sts: sts(), + consoleTokens: { + [consoleCredentialKey({ ...TARGET, gateway: profile().console_gateway })]: { + token: "new-console", + }, + }, + }), + ); + const nextReference = readConfigFile().aliyun_oauth!.session_ref; + const before = instance.values.get(nextReference); + await instance.provider.saveConsoleCredential(oldCredential); + expect(instance.values.get(nextReference)).toBe(before); + expect((await instance.provider.getConsoleCredential(TARGET))?.token).toBe("new-console"); + expect(transport).not.toHaveBeenCalled(); + }); + + test("endpoint changes during STS exchange stop the caller and preserve new metadata", async () => { + const instance = await setup(); + const entered = deferred(); + const release = deferred(); + transport.mockImplementation(async () => { + entered.resolve(); + await release.promise; + return stsResponse(); + }); + const result = instance.provider.getCredential(); + await entered.promise; + await writeConfigFile({ aliyun_oauth: profile({ modelstudio_host: "changed.example.test" }) }); + const before = await configText(); + release.resolve(); + await expect(result).rejects.toBeInstanceOf(CredentialError); + expect(await configText()).toBe(before); + expect(transport).toHaveBeenCalledTimes(1); + }); + + test("credential endpoint fingerprint is checked again before signing", async () => { + const instance = await setup({ oauthSession: session({ sts: sts() }) }); + const credential = await instance.provider.getCredential(); + await writeConfigFile({ aliyun_oauth: profile({ modelstudio_host: "changed.example.test" }) }); + expect(() => + instance.provider.resolveHost("modelstudio.cn-beijing.aliyuncs.com", credential), + ).toThrow(CredentialError); + expect(transport).not.toHaveBeenCalled(); + }); + + test("provider and auth store stay in their original configuration directory", async () => { + const instance = await setup({ configName: "first", oauthSession: session({ sts: sts() }) }); + const another = enterIsolatedHome(); + try { + await writeConfigFile({ aliyun_oauth: profile({ session_ref: OTHER_REFERENCE }) }); + const before = readConfigFile(); + expect((await instance.provider.getCredential()).sessionRef).toBe(REFERENCE); + await instance.auth.login({ workspace_id: "first-workspace" }); + expect(readConfigFile()).toEqual(before); + expect(readConfigFile("first", instance.sources.configPath).workspace_id).toBe( + "first-workspace", + ); + expect(instance.auth.describe().aliyunOAuth?.session_ref).toBe(REFERENCE); + } finally { + another.restore(); + } + expect(transport).not.toHaveBeenCalled(); + }); + + test("environment credential inputs are snapshotted for the invocation", async () => { + const instance = await setup({ + file: {}, + env: { BAILIAN_ACCESS_KEY_ID: "first-id", BAILIAN_ACCESS_KEY_SECRET: "first-secret" }, + }); + instance.sources.env.BAILIAN_ACCESS_KEY_ID = "second-id"; + instance.sources.env.BAILIAN_ACCESS_KEY_SECRET = "second-secret"; + expect((await instance.provider.getCredential()).accessKeyId).toBe("first-id"); + expect(transport).not.toHaveBeenCalled(); + }); +}); + +describe("cross-process OAuth session serialization", () => { + test("a real child waits on the shared session lock and reuses the parent's rotated session without RT replay", async () => { + // Necessary process boundary: a per-provider single-flight Map cannot protect a second CLI process. + // One parent/child pair exercises the actual EEXIST lock path and durable refresh recovery; + // the on-disk store contains only synthetic fixture JSON, never an OS key or real credentials. + const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); + const fakeFile = join(isolation.configDir, "fixture-session.json"); + await writeFile(fakeFile, JSON.stringify(session({ accessTokenExpiresAt: NOW })), { + mode: 0o600, + }); + const store: OAuthSecretStore = { + read: async () => readFile(fakeFile, "utf8"), + write: async (_reference, raw) => { + await writeFile(fakeFile, raw, { mode: 0o600 }); + }, + remove: async () => { + throw new Error("Unexpected fixture removal"); + }, + }; + const provider = createOpenApiCredentialProvider(instance.sources, deps, { + store, + directory: isolation.configDir, + }); + const refreshEntered = deferred(); + const allowRefresh = deferred(); + transport.mockImplementation(async (endpoint) => { + if (endpointUrl(endpoint).endsWith("/v1/token")) { + refreshEntered.resolve(); + await allowRefresh.promise; + return tokenResponse(); + } + expect(JSON.parse(await readFile(fakeFile, "utf8"))).toMatchObject({ + refreshToken: ROTATED_REFRESH, + refreshPending: false, + }); + return stsResponse(); + }); + const parentResult = provider.getCredential(); + let child: FixtureChild | undefined; + try { + await refreshEntered.promise; + child = startLockContender(instance.sources, fakeFile); + await child.contended; + expect(JSON.parse(await readFile(fakeFile, "utf8"))).toMatchObject({ + refreshPending: true, + refreshToken: REFRESH, + }); + allowRefresh.resolve(); + const [parent, result] = await Promise.all([parentResult, child.completion]); + expect(result.code, result.stderr).toBe(0); + expect(result.stderr).toBe(""); + expect(JSON.parse(result.stdout)).toEqual({ + accessKeyId: parent.accessKeyId, + sessionRef: parent.sessionRef, + }); + expect( + transport.mock.calls.map(([endpoint]) => new URL(endpointUrl(endpoint)).pathname), + ).toEqual(["/v1/token", "/v1/exchange"]); + expect(JSON.parse(await readFile(fakeFile, "utf8"))).toMatchObject({ + refreshToken: ROTATED_REFRESH, + refreshPending: false, + sts: sts(), + }); + expect(await readdir(join(isolation.configDir, "oauth"))).toEqual([]); + expectNoPlaintextConfig(await configText()); + } finally { + allowRefresh.resolve(); + await parentResult.catch(() => {}); + if (child) { + if (child.process.exitCode === null) child.process.kill(); + await child.completion.catch(() => {}); + } + } + }); +}); diff --git a/packages/runtime/src/create-cli.ts b/packages/runtime/src/create-cli.ts index 4969e9ac8..2762fb078 100644 --- a/packages/runtime/src/create-cli.ts +++ b/packages/runtime/src/create-cli.ts @@ -1,5 +1,5 @@ import { CommandRegistry } from "./registry.ts"; -import { resolve } from "./resolve.ts"; +import { resolve, type Resolution } from "./resolve.ts"; import { buildCommandSchema, serializeCommandSchema } from "./introspect.ts"; import { compose, @@ -20,6 +20,7 @@ import type { Settings, ResolutionSources, OutputDiagnostic, + PreControlPlane, } from "bailian-cli-core"; import { formatCommand, @@ -66,6 +67,9 @@ export interface CliOptions { quickStartTasks?: readonly string[]; /** Command Packs accepted by this product. Omit when the product supports none. */ commandPacks?: CommandPackPolicy; + /** Resolve pre-release routing once per invocation; omitted by hosts without a control-plane switch. */ + preControlPlane?: () => PreControlPlane | undefined; + validatePreControlPlaneCommand?: (path: string) => void; } export interface Cli { @@ -117,6 +121,31 @@ function presentationFlags(argv: string[]): Partial { return flags; } +function isPresentationOnly(resolution?: Resolution): boolean { + return ( + resolution?.kind === "help" || + resolution?.kind === "version" || + resolution?.kind === "introspect" + ); +} + +function usesModelConfig(resolution: Resolution, registry: CommandRegistry): boolean { + if (resolution.kind === "usageError") return resolution.command?.auth === "apiKey"; + if (resolution.kind !== "run" && resolution.kind !== "help") return false; + const target = resolution.kind === "run" ? resolution : registry.locate(resolution.path); + if (target.kind !== "run" && target.kind !== "leaf") return false; + const { apiKey, console, openApi } = resolution.parsedFlags; + return ( + target.command.auth === "apiKey" || + // Login itself is auth-free, so only the model login mode uses the model file. + (resolution.path.join(" ") === "auth login" && + typeof apiKey === "string" && + Boolean(apiKey.trim()) && + !console && + !openApi) + ); +} + interface ProcessOutputContext { getReporter: () => OutputReporter; localize: (text: LocalizedText) => string; @@ -240,12 +269,12 @@ export function createCli(commands: Record, opts: CliOptions async function dispatch( registry: CommandRegistry, - argv: string[], + res: Resolution, localize: (text: LocalizedText) => string, initialSources: ResolutionSources, configureOutput: (settings: Pick) => OutputReporter, + preControlPlane?: PreControlPlane, ): Promise { - const res = resolve(argv, registry, localize); const command = res.kind === "run" || res.kind === "usageError" ? res.command : undefined; const outputSettings = buildOutputSettings({ ...initialSources, @@ -319,7 +348,39 @@ export function createCli(commands: Record, opts: CliOptions // 校验通过 → 建源、解析 settings、组 ctx,进中间件执行命令。 const sources = { ...initialSources, flags: globalFlags }; const settings = { ...buildSettings(sources), ...outputSettings }; + let controlSources: ResolutionSources | undefined; + if (preControlPlane && !sources.preControlPlane) { + // Keep model options (including workspace and output), but never use + // a production Profile's Console scope on the pre-release gateway. + settings.preControlPlane = preControlPlane; + settings.consoleRegion = globalFlags.consoleRegion || undefined; + settings.consoleSite = + (globalFlags.consoleSite as Settings["consoleSite"]) || undefined; + settings.consoleSwitchAgent = globalFlags.consoleSwitchAgent || undefined; + if (res.command.optionalConsole) { + try { + const selected = buildSources( + globalFlags, + (warning) => reporter.output.warning(warning), + preControlPlane, + ); + const { consoleRegion, consoleSite, consoleSwitchAgent } = buildSettings(selected); + Object.assign(settings, { consoleRegion, consoleSite, consoleSwitchAgent }); + controlSources = selected; + } catch { + reporter.output.warning({ + code: "PRE_CONSOLE_CONFIG_UNAVAILABLE", + message: { + "en-US": + "Pre-release Console configuration is unavailable; continuing without its credentials.", + "zh-CN": "预发控制台配置不可用;将不使用控制台凭据继续执行。", + }, + }); + } + } + } const ctx: RunContext = { + hasCommand, commandPath: (command) => registry.commandPath(command), identity, output: reporter.output, @@ -330,8 +391,14 @@ export function createCli(commands: Record, opts: CliOptions localize, settings, sources, - configStore: makeConfigStore(sources.configName), - authStore: makeAuthStore(sources), + controlSources, + configStore: makeConfigStore(sources.configName, sources.configPath), + authStore: makeAuthStore(sources, { + identity, + timeout: settings.timeout, + debug: (diagnostic) => reporter.output.debug(diagnostic), + warning: (diagnostic) => reporter.output.warning(diagnostic), + }), commandPacks: createCommandPackManager(identity, commandPackPolicy, reporter.output), setRecoveryConfigName: (name) => reporter.setRecoveryConfigName(name), client: new Client({ @@ -346,7 +413,7 @@ export function createCli(commands: Record, opts: CliOptions } catch (err) { // 裸调用(命令后什么都没写)下的 UsageError → 当"还没写完",打 help、exit 0; // 写了 flag 却无效、或执行时报错 → 报错、exit 2。 - if (err instanceof UsageError && res.rest.length === 0) { + if (err instanceof UsageError && res.rest.length === 0 && !preControlPlane) { registry.printHelp(res.path, process.stderr); return; } @@ -383,7 +450,47 @@ export function createCli(commands: Record, opts: CliOptions const warnings: OutputDiagnostic[] = []; const cleanup = installProcessHandlers(() => reporter, localize); try { - const sources = buildSources(flags, (warning) => warnings.push(warning)); + let preControlPlane: PreControlPlane | undefined; + let controlPlaneError: UsageError | undefined; + try { + preControlPlane = opts.preControlPlane?.(); + } catch (error) { + if (!(error instanceof UsageError)) throw error; + controlPlaneError = error; + } + + let registry: CommandRegistry | undefined; + let resolution: Resolution | undefined; + let sourcePlane = preControlPlane; + if (preControlPlane || controlPlaneError) { + // Only the pre-release switch needs to identify the command before + // loading preferences. The registry localizes lazily after selection. + registry = await getRegistry({ + get language() { + return translator.language; + }, + localize, + }); + resolution = resolve(argv, registry, localize); + if (controlPlaneError && !isPresentationOnly(resolution)) throw controlPlaneError; + if (preControlPlane && resolution.kind === "run") { + opts.validatePreControlPlaneCommand?.( + (registry.commandPath(resolution.command) ?? resolution.path).join(" "), + ); + } + if (usesModelConfig(resolution, registry)) sourcePlane = undefined; + } + + let sources: ResolutionSources = { flags, env: process.env, file: {} }; + if (!controlPlaneError) { + try { + sources = buildSources(flags, (warning) => warnings.push(warning), sourcePlane); + } catch (error) { + // Help/version must remain usable to recover from bad pre-release + // configuration. Never read another environment as a fallback. + if (!preControlPlane || !isPresentationOnly(resolution)) throw error; + } + } const recoveryConfigName = resolveRecoveryConfigName(sources); translator = createTranslator(sources.file.language ?? DEFAULT_LANGUAGE); reporter = createOutputReporter({ @@ -394,18 +501,29 @@ export function createCli(commands: Record, opts: CliOptions configName: recoveryConfigName, }); setupProxyFromEnv(); - const registry = await getRegistry(translator); - await dispatch(registry, argv, localize, sources, (settings) => { - reporter = createOutputReporter({ - settings, - localize, - commandPrefix, - hasCommand, - configName: recoveryConfigName, - }); - for (const warning of warnings.splice(0)) reporter.output.warning(warning); - return reporter; - }); + registry ??= await getRegistry(translator); + // On parser failures, render the diagnostic in the selected language. + if (!resolution || resolution.kind === "usageError") { + resolution = resolve(argv, registry, localize); + } + await dispatch( + registry, + resolution, + localize, + sources, + (settings) => { + reporter = createOutputReporter({ + settings, + localize, + commandPrefix, + hasCommand, + configName: recoveryConfigName, + }); + for (const warning of warnings.splice(0)) reporter.output.warning(warning); + return reporter; + }, + preControlPlane, + ); } catch (error) { for (const warning of warnings.splice(0)) reporter.output.warning(warning); await flushTelemetry(1000); diff --git a/packages/runtime/src/error-handler.ts b/packages/runtime/src/error-handler.ts index 292817044..5f24c638a 100644 --- a/packages/runtime/src/error-handler.ts +++ b/packages/runtime/src/error-handler.ts @@ -48,7 +48,25 @@ function recoveryCommand(commandPrefix: string, args: string, configName?: strin } /** Complete recovery text supplied before Console errors can be wrapped by commands. */ -export function consoleRecoveryHint(commandPrefix: string, configName?: string): string { +export function aliyunRecoveryHint( + commandPrefix: string, + configName?: string, + localize: Localize = english, +): string { + const command = recoveryCommand(commandPrefix, "auth --login aliyun", configName); + return localize({ + "en-US": `Run \`${command}\` to sign in to Aliyun again.`, + "zh-CN": `请运行 \`${command}\` 重新登录阿里云。`, + }); +} + +export function consoleRecoveryHint( + commandPrefix: string, + configName?: string, + aliyun = false, + localize: Localize = english, +): string { + if (aliyun) return aliyunRecoveryHint(commandPrefix, configName, localize); return `Run \`${recoveryCommand(commandPrefix, "auth login --console", configName)}\` to sign in or refresh your console session.`; } @@ -110,6 +128,21 @@ export function errorHint( let hint = error.hint; if (error instanceof CredentialError) { switch (error.reason) { + case "changed-openapi-identity": + return localize({ + "en-US": + "Credentials or endpoints changed during this command; rerun it using the intended profile.", + "zh-CN": "命令执行期间凭据或端点已变更,请使用目标配置重新执行。", + }); + case "aliyun-oauth-session": + case "missing-aliyun-session": + case "aliyun-refresh-uncertain": + return options.hasCommand?.("auth") + ? aliyunRecoveryHint(commandPrefix, configName, localize) + : localize({ + "en-US": "Use the CLI that manages this profile to sign in to Aliyun again.", + "zh-CN": "请使用管理此配置的 CLI 重新登录阿里云。", + }); case "missing-api-key": hint = `Set DASHSCOPE_API_KEY, pass --api-key, or run \`${recoveryCommand(commandPrefix, "auth login", configName)}\`.`; break; diff --git a/packages/runtime/src/middleware.ts b/packages/runtime/src/middleware.ts index 3b3d26f8b..3b1e282f2 100644 --- a/packages/runtime/src/middleware.ts +++ b/packages/runtime/src/middleware.ts @@ -1,4 +1,4 @@ -import { consoleRecoveryHint } from "./error-handler.ts"; +import { consoleRecoveryHint, aliyunRecoveryHint } from "./error-handler.ts"; import type { AnyCommand, CommandOutput, @@ -10,7 +10,6 @@ import type { CredentialSource, FlagsDef, Identity, - OpenApiCredential, ParsedFlags, ResolutionSources, Settings, @@ -24,10 +23,13 @@ import { isModelConnectionSourceMismatch, resolveApiKey, resolveConsole, - resolveOpenApi, + createOpenApiCredentialProvider, + bindOpenApiConsoleCredentials, readCaller, + requirePreConsoleGateway, resolveModelBaseUrlState, resolveModelConnectionProvenance, + resolveRecoveryConfigName, selectApiKeyResolutionSources, trackCommandExecution, } from "bailian-cli-core"; @@ -48,6 +50,7 @@ import { prepareCommand } from "./preparation.ts"; * {@link authStage}). A stage reads these and may augment them before `next()`. */ export interface RunContext { + hasCommand?: (path: string) => boolean; commandPath?: (command: AnyCommand) => string[] | undefined; prepared?: unknown; /** 静态产品身份(binName/version/npmPackage/clientName)。 */ @@ -66,6 +69,8 @@ export interface RunContext { settings: Settings; /** 解析源:provider/访问器用;业务命令不可见(窄视图类型不含此字段)。 */ sources: ResolutionSources; + /** Optional pre-release Console sources for a model command. Missing means no Console auth. */ + controlSources?: ResolutionSources; /** 配置持久化能力;lint 限定 commands/config/** 使用。 */ configStore: ConfigStore; /** 鉴权持久化能力;lint 限定 commands/auth/** 使用。 */ @@ -189,15 +194,43 @@ export function compose(stack: Middleware[]): (ctx: RunContext) => Promise */ export const authStage: Middleware = async (ctx, next) => { const { command, settings, sources } = ctx; + const debug = (diagnostic: Parameters[0]) => ctx.output.debug(diagnostic); + const controlRecoveryConfigName = (controlSources: ResolutionSources) => + controlSources === sources + ? settings.recoveryConfigName + : resolveRecoveryConfigName(controlSources); + const createProvider = (controlSources: ResolutionSources) => + createOpenApiCredentialProvider(controlSources, { + identity: ctx.identity, + timeout: settings.timeout, + debug, + recoveryHint: ctx.hasCommand?.("auth") + ? aliyunRecoveryHint( + formatCommand(ctx.identity), + controlRecoveryConfigName(controlSources), + ctx.localize, + ) + : ctx.localize({ + "en-US": "Use the CLI that manages this profile to sign in to Aliyun again.", + "zh-CN": "请使用管理此配置的 CLI 重新登录阿里云。", + }), + }); + // Console credentials do not fall back; keep the selected control profile pin. + const controlRecoveryHint = (controlSources: ResolutionSources) => + consoleRecoveryHint( + formatCommand(ctx.identity), + controlRecoveryConfigName(controlSources), + Boolean(controlSources.file.aliyun_oauth?.console_enabled && ctx.hasCommand?.("auth")), + ctx.localize, + ); const base = { identity: ctx.identity, settings, - // Console credentials do not fall back; keep the selected profile pin. - consoleRecoveryHint: consoleRecoveryHint( - formatCommand(ctx.identity), - settings.recoveryConfigName, - ), - debug: (diagnostic: Parameters[0]) => ctx.output.debug(diagnostic), + consoleRecoveryHint: + settings.preControlPlane && command.auth === "apiKey" + ? undefined + : controlRecoveryHint(sources), + debug, ...resolveModelBaseUrlState(sources), }; if (command.auth === "apiKey") { @@ -228,37 +261,81 @@ export const authStage: Middleware = async (ctx, next) => { } catch (err) { if (!settings.dryRun || command.prepare) throw err; } - ctx.client = new Client({ - ...base, - ...resolveModelBaseUrlState(apiSources), - apiCred: cred, - }); - // Optional console precheck surface: inject the console credential when it - // resolves, but never fail an apiKey command because the console session is - // missing or expired. Commands must treat `client.console` calls as - // best-effort and catch AUTH errors themselves. - if (command.optionalConsole) { + const apiClientDeps = { ...base, ...resolveModelBaseUrlState(apiSources), apiCred: cred }; + ctx.client = new Client(apiClientDeps); + // In pre-release mode never fall back from an unavailable Console source to + // the model Profile, even when that Profile has valid Console credentials. + const controlSources = settings.preControlPlane ? ctx.controlSources : sources; + if (command.optionalConsole && controlSources) { try { - const consoleCred = resolveConsole(sources); - ctx.client = new Client({ - ...base, - ...resolveModelBaseUrlState(apiSources), - apiCred: cred, - consoleCred, - }); + if (settings.preControlPlane) { + requirePreConsoleGateway(settings.preControlPlane, { + region: settings.consoleRegion, + site: settings.consoleSite, + }); + } + let consoleCred: ConsoleCredential | undefined; + try { + consoleCred = resolveConsole(controlSources); + } catch { + /* An OAuth profile or static AK/SK may still supply a Console session. */ + } + const provider = + settings.preControlPlane || + (!consoleCred && controlSources.file.aliyun_oauth?.console_enabled) + ? createProvider(controlSources) + : undefined; + if (!consoleCred) provider?.assertAvailable("console"); + if (consoleCred || provider) { + ctx.client = new Client({ + ...apiClientDeps, + settings: + controlSources === sources + ? settings + : { + ...settings, + // Console refresh must persist only to the selected pre-release Profile. + configPath: controlSources.configPath, + configName: controlSources.configName, + recoveryConfigName: controlRecoveryConfigName(controlSources), + }, + consoleRecoveryHint: controlRecoveryHint(controlSources), + consoleCred, + ...(provider + ? { + openApiProvider: provider, + resolveConsoleOpenApiCredential: () => provider.getCredential("console"), + } + : {}), + }); + } } catch { - // Best-effort only — the command's apiKey flow continues. + if (settings.preControlPlane) { + ctx.output.warning({ + code: "PRE_CONSOLE_UNAVAILABLE", + message: { + "en-US": "Pre-release Console is unavailable; continuing with the model API only.", + "zh-CN": "预发控制台不可用,将仅通过模型 API 继续执行。", + }, + }); + } } } if (cred && !command.prepare) maybeShowStatusBar(settings, cred.token, cred, ctx.output); } else if (command.auth === "console") { + if (settings.preControlPlane && (!settings.dryRun || command.prepare)) { + requirePreConsoleGateway(settings.preControlPlane, { + region: settings.consoleRegion, + site: settings.consoleSite, + }); + } + const provider = createProvider(sources); let cred: ConsoleCredential | undefined; - let exchangeCredential: OpenApiCredential | undefined; try { cred = resolveConsole(sources); } catch (error) { try { - exchangeCredential = resolveOpenApi(sources); + provider.assertAvailable("console"); } catch (credentialError) { if (!settings.dryRun || command.prepare) { throw credentialError instanceof CredentialError && @@ -271,16 +348,27 @@ export const authStage: Middleware = async (ctx, next) => { ctx.client = new Client({ ...base, consoleCred: cred, - resolveConsoleOpenApiCredential: () => exchangeCredential ?? resolveOpenApi(sources), + openApiProvider: provider, + resolveConsoleOpenApiCredential: () => provider.getCredential("console"), }); } else if (command.auth === "openapi") { - let cred: OpenApiCredential | undefined; + const provider = createProvider(sources); try { - cred = resolveOpenApi(sources); - } catch (err) { - if (!settings.dryRun || command.prepare) throw err; + provider.assertAvailable(); + } catch (error) { + if (!settings.dryRun || command.prepare) throw error; } - ctx.client = new Client({ ...base, openApiCred: cred }); + const boundProvider = bindOpenApiConsoleCredentials(provider); + ctx.client = new Client({ + ...base, + settings: { + ...settings, + consoleRegion: settings.consoleRegion ?? "cn-beijing", + consoleSite: settings.consoleSite ?? "domestic", + }, + openApiProvider: boundProvider, + resolveConsoleOpenApiCredential: () => boundProvider.getCredential(), + }); } await next(); }; diff --git a/packages/runtime/tests/console-aksk-auth.test.ts b/packages/runtime/tests/console-aksk-auth.test.ts index 50dba2765..5fae900ad 100644 --- a/packages/runtime/tests/console-aksk-auth.test.ts +++ b/packages/runtime/tests/console-aksk-auth.test.ts @@ -1,17 +1,22 @@ import { afterEach, expect, test, vi } from "vite-plus/test"; -import { buildIsolatedCliEnv, withIsolatedHome } from "e2e/isolation"; +import { buildIsolatedCliEnv, withIsolatedHome, enterIsolatedHome } from "e2e/isolation"; import { runInProcess } from "e2e/in-process"; import { Client, defineCommand, CredentialError, + ExitCode, buildSettings, describeAuthState, httpTransport, readConfigFile, writeConfigFile, + getConfigPath, + readConfigProfiles, + makeAuthStore, type ConfigFile, type ResolutionSources, + type LocalizedText, } from "bailian-cli-core"; import { authStage, type RunContext } from "../src/middleware.ts"; import { createOutputReporter } from "../src/output/reporter.ts"; @@ -43,6 +48,7 @@ async function context( identity, settings, sources, + localize: (text: LocalizedText) => (typeof text === "string" ? text : text["en-US"]), command: { auth: "console", ...(prepared @@ -101,6 +107,53 @@ function backend( }; } +test("missing pre-release Console routing never reuses an online token or interrupts the model path", async () => { + await withIsolatedHome(async () => { + const original = await context({ + api_key: "fixture-model-key", + access_token: "fixture-online-console", + }); + const ctx: RunContext = { + ...original, + path: ["fixture", "inference"], + command: defineCommand({ + auth: "apiKey", + optionalConsole: true, + description: "Fixture", + run: async () => {}, + }), + settings: { ...original.settings, preControlPlane: {} }, + controlSources: { + flags: {}, + file: {}, + env: {}, + preControlPlane: {}, + configPath: getConfigPath({}), + }, + }; + const warning = vi.spyOn(ctx.output, "warning").mockImplementation(() => {}); + const fetch = vi + .spyOn(httpTransport, "fetch") + .mockResolvedValue(Response.json({ result: "fixture" })); + await authStage(ctx, async () => { + await expect(ctx.client.console("fixture.catalog", {})).rejects.toMatchObject({ + exitCode: ExitCode.AUTH, + }); + await expect(ctx.client.requestJson({ path: "/fixture/model" })).resolves.toEqual({ + result: "fixture", + }); + }); + expect(warning).toHaveBeenCalledWith( + expect.objectContaining({ code: "PRE_CONSOLE_UNAVAILABLE" }), + ); + expect(fetch).toHaveBeenCalledTimes(1); + expect(fetch.mock.calls[0]?.[0]).toBe("https://dashscope.aliyuncs.com/fixture/model"); + expect(new Headers(fetch.mock.calls[0]?.[1]?.headers).get("authorization")).toBe( + "Bearer fixture-model-key", + ); + }); +}); + test.each([ { name: "bailian-env", @@ -146,6 +199,118 @@ test.each([ }, ); +test("mixed OpenAPI commands derive Console credentials from their primary identity", async () => { + await withIsolatedHome(async () => { + const original = await context( + { access_token: "console-a", access_key_id: "account-a", access_key_secret: "secret-a" }, + {}, + { accessKeyId: "account-b", accessKeySecret: "secret-b" }, + ); + const ctx = { ...original, command: { ...original.command, auth: "openapi" as const } }; + const calls: Array<{ url: URL; headers: Headers }> = []; + vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const url = new URL(input instanceof Request ? input.url : input); + const headers = new Headers(init?.headers); + calls.push({ url, headers }); + if (url.pathname === "/modelstudio/cli/generateAccessToken") + return Response.json({ cliAccessToken: "console-b" }); + if (url.pathname === "/cli/api.json") + return Response.json({ data: { success: true, uid: "account-b" } }); + return Response.json({ Success: true }); + }); + await authStage(ctx, async () => { + await ctx.client.console("login.info", {}); + await ctx.client.openApiQueryJson({ + host: "modelstudio.cn-beijing.aliyuncs.com", + path: "/fixture/openapi", + action: "FixtureRead", + version: "2026-02-10", + method: "POST", + queryParams: {}, + }); + }); + expect(calls).toHaveLength(3); + expect( + calls + .filter((call) => call.url.pathname !== "/cli/api.json") + .every((call) => call.headers.get("authorization")?.includes("Credential=account-b")), + ).toBe(true); + expect( + calls.find((call) => call.url.pathname === "/cli/api.json")!.headers.get("authorization"), + ).toBe("Bearer console-b"); + expect(calls.every((call) => call.headers.get("authorization") !== "Bearer console-a")).toBe( + true, + ); + }); +}); + +test("static Console refresh remains bound to the original directory", async () => { + await withIsolatedHome(async () => { + const ctx = await context({ + access_token: "old-token", + access_key_id: "local-ak", + access_key_secret: "local-sk", + }); + const originalPath = getConfigPath(); + let another: ReturnType | undefined; + try { + backend({ + gateway: async (_url, headers) => { + if (headers.get("authorization") === "Bearer old-token") + return Response.json({ + data: { success: false, errorCode: "BailianGateway.Login.NotLogined" }, + }); + another = enterIsolatedHome(); + await writeConfigFile({ access_token: "other-directory-token" }); + return Response.json({ data: { success: true } }); + }, + }); + await authStage(ctx, () => ctx.client.console("test.api", {}).then(() => {})); + expect(readConfigFile().access_token).toBe("other-directory-token"); + expect(readConfigProfiles().named.selected).toBeUndefined(); + expect(readConfigFile("selected", originalPath).access_token).toBe("fresh-token"); + } finally { + another?.restore(); + } + }); +}); + +test("a late static Console refresh cannot restore a logged-out token", async () => { + await withIsolatedHome(async () => { + const ctx = await context({ + access_token: "old-token", + access_key_id: "local-ak", + access_key_secret: "local-sk", + }); + let entered!: () => void; + let release!: () => void; + const freshEntered = new Promise((resolve) => { + entered = resolve; + }); + const freshRelease = new Promise((resolve) => { + release = resolve; + }); + backend({ + gateway: async (_url, headers) => { + if (headers.get("authorization") === "Bearer old-token") + return Response.json({ + data: { success: false, errorCode: "BailianGateway.Login.NotLogined" }, + }); + entered(); + await freshRelease; + return Response.json({ data: { success: true } }); + }, + }); + const request = authStage(ctx, () => ctx.client.console("test.api", {}).then(() => {})); + await freshEntered; + await makeAuthStore(ctx.sources).logout("all"); + release(); + await request; + expect(readConfigFile("selected").access_token).toBeUndefined(); + expect(readConfigFile("selected").access_key_id).toBeUndefined(); + }); +}); + test("existing token is used without resolving unused partial AK/SK", async () => { await withIsolatedHome(async () => { const ctx = await context( diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index e9e000da1..0ac098130 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -9,32 +9,76 @@ Index: [index.md](index.md) | Command | Authentication | Description | | ------------------------------- | -------------- | -------------------------------------------------------------------------------------------- | -| `bl auth generate-access-token` | No Auth | Generate a CLI access token using OpenAPI AK/SK | +| `bl auth` | No Auth | Authenticate with Aliyun OAuth | +| `bl auth generate-access-token` | AK/SK | Generate a CLI access token using OpenAPI credentials | | `bl auth login` | No Auth | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | | `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | | `bl auth status` | No Auth | Show current authentication state | ## Command details +### `bl auth` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | +| **Name** | `auth` | +| **Description** | Authenticate with Aliyun OAuth | +| **Authentication** | No Auth | +| **Usage** | `bl auth --login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------------------- | ------ | -------- | -------------------------------------------------------------------------------------------- | +| `--login ` | string | yes | Login method: aliyun | +| `--client-id ` | string | no | OAuth client ID; required for the first login outside pre-release | +| `--scope ` | string | no | OAuth scope (default: openid /internal/bailian/cli) | +| `--oauth-base-url ` | string | no | OAuth token service origin (production default: https://oauth.aliyun.com) | +| `--authorization-url ` | string | no | Explicit authorization URL; required for the first login outside pre-release | +| `--modelstudio-host ` | string | no | Model Studio POP hostname override (production default: modelstudio.cn-beijing.aliyuncs.com) | +| `--console-gateway ` | string | no | Console gateway origin override (production default: https://bailian-cs.console.aliyun.com) | +| `--bailiancontrol-host ` | string | no | Optional Bailian Control OpenAPI hostname | +| `--console-region ` | string | no | Console region (only cn-beijing; default: cn-beijing) | +| `--no-browser` | switch | no | Do not open the browser automatically; still wait for the local callback | + +#### Notes + +- Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. No device flow or remote callback import is supported. +- Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match. + +#### Examples + +```bash +bl auth --login aliyun --client-id --authorization-url +``` + +```bash +bl auth --login aliyun --client-id --authorization-url --modelstudio-host --console-gateway +``` + ### `bl auth generate-access-token` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------------------------- | -| **Name** | `auth generate-access-token` | -| **Description** | Generate a CLI access token using OpenAPI AK/SK | -| **Authentication** | No Auth | -| **Usage** | `bl auth generate-access-token --access-key-id --access-key-secret --security-token ` | +| Field | Value | +| ------------------ | ----------------------------------------------------- | +| **Name** | `auth generate-access-token` | +| **Description** | Generate a CLI access token using OpenAPI credentials | +| **Authentication** | AK/SK | +| **Usage** | `bl auth generate-access-token [flags]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------ | ------ | -------- | ---------------------------------------------------- | -| `--access-key-id ` | string | yes | Alibaba Cloud Access Key ID | -| `--access-key-secret ` | string | yes | Alibaba Cloud Access Key Secret | -| `--security-token ` | string | no | Alibaba Cloud STS Security Token to store (optional) | +| Flag | Type | Required | Description | +| --------------------------- | ------ | -------- | ---------------------------------------------------------------------- | +| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID) | +| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET) | +| `--security-token ` | string | no | Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN) | #### Examples +```bash +bl auth generate-access-token +``` + ```bash bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxxx --security-token ``` @@ -50,18 +94,18 @@ bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxx #### Flags -| Flag | Type | Required | Description | -| ----------------------------------------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--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 | -| `--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 | -| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID to store | -| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret to store | +| Flag | Type | Required | Description | +| ----------------------------------------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--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). Outside pre-release, 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 | +| `--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 | +| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID to store | +| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret to store | #### Examples @@ -92,15 +136,20 @@ bl auth login --open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx | **Name** | `auth logout` | | **Description** | Clear stored credentials; full logout also clears the model Base URL | | **Authentication** | No Auth | -| **Usage** | `bl auth logout [--console \| --open-api] [--dry-run]` | +| **Usage** | `bl auth logout [--console \| --open-api \| --aliyun] [--dry-run]` | #### Flags | Flag | Type | Required | Description | | ------------ | ------ | -------- | ----------------------------------------------------------------------- | +| `--aliyun` | switch | no | Revoke and remove only the Aliyun OAuth session | | `--console` | switch | no | Only clear the console access_token, keep api_key intact | | `--open-api` | switch | no | Only clear OpenAPI AK/SK/STS credentials, keep other credentials intact | +#### Notes + +- Full logout or --aliyun revokes the OAuth refresh token. Partial Console/OpenAPI logout disables only that domain. Pre-release logout leaves model and production credentials intact. + #### Examples ```bash @@ -115,6 +164,10 @@ bl auth logout --console bl auth logout --open-api ``` +```bash +bl auth logout --aliyun +``` + ```bash bl auth logout --dry-run ``` diff --git a/skills/bailian-cli/reference/index.md b/skills/bailian-cli/reference/index.md index faa45c63a..5ffbf805b 100644 --- a/skills/bailian-cli/reference/index.md +++ b/skills/bailian-cli/reference/index.md @@ -28,7 +28,8 @@ Use this index for the skill-scoped quick index and global flags. | `bl alert update` | Console | Update a model alert rule (full replacement; same fields as create) | [alert.md](alert.md) | | `bl app call` | API Key | [Deprecated] Call a Bailian application (agent or workflow) | [app.md](app.md) | | `bl app list` | Console | [Deprecated] List Bailian applications | [app.md](app.md) | -| `bl auth generate-access-token` | No Auth | Generate a CLI access token using OpenAPI AK/SK | [auth.md](auth.md) | +| `bl auth` | No Auth | Authenticate with Aliyun OAuth | [auth.md](auth.md) | +| `bl auth generate-access-token` | AK/SK | Generate a CLI access token using OpenAPI credentials | [auth.md](auth.md) | | `bl auth login` | No Auth | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | [auth.md](auth.md) | | `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | [auth.md](auth.md) | | `bl auth status` | No Auth | Show current authentication state | [auth.md](auth.md) | @@ -134,7 +135,7 @@ Use this index for the skill-scoped quick index and global flags. | `bl usage stats` | Console | Query model usage statistics | [usage.md](usage.md) | | `bl usage summary` | Console | Show a unified usage summary: free-tier quota and recent usage overview | [usage.md](usage.md) | | `bl usage token-plan` | Console | Show Token Plan quota usage | [usage.md](usage.md) | -| `bl workspace init` | No Auth | Initialize Bailian workspace and activate postpaid services | [workspace.md](workspace.md) | +| `bl workspace init` | AK/SK | Initialize Bailian workspace and activate postpaid services | [workspace.md](workspace.md) | | `bl workspace list` | Console | List all workspaces | [workspace.md](workspace.md) | ## By group @@ -145,7 +146,7 @@ Use this index for the skill-scoped quick index and global flags. | `agents` | `security alerts`, `security overview` | [agents.md](agents.md) | | `alert` | `create`, `delete`, `disable`, `enable`, `history`, `list`, `metrics`, `template create`, `template delete`, `template list`, `template update`, `update` | [alert.md](alert.md) | | `app` | `call`, `list` | [app.md](app.md) | -| `auth` | `generate-access-token`, `login`, `logout`, `status` | [auth.md](auth.md) | +| `auth` | `(root)`, `generate-access-token`, `login`, `logout`, `status` | [auth.md](auth.md) | | `batch` | `cancel`, `convert`, `create`, `download`, `get`, `list` | [batch.md](batch.md) | | `cmodel` | `base-models`, `delete`, `get`, `import`, `list`, `watch` | [cmodel.md](cmodel.md) | | `config` | `agent`, `list`, `set`, `show`, `ui`, `use` | [config.md](config.md) | diff --git a/skills/bailian-cli/reference/workspace.md b/skills/bailian-cli/reference/workspace.md index 418e2ca43..21a192555 100644 --- a/skills/bailian-cli/reference/workspace.md +++ b/skills/bailian-cli/reference/workspace.md @@ -9,30 +9,34 @@ Index: [index.md](index.md) | Command | Authentication | Description | | ------------------- | -------------- | ----------------------------------------------------------- | -| `bl workspace init` | No Auth | Initialize Bailian workspace and activate postpaid services | +| `bl workspace init` | AK/SK | Initialize Bailian workspace and activate postpaid services | | `bl workspace list` | Console | List all workspaces | ## Command details ### `bl workspace init` -| Field | Value | -| ------------------ | ------------------------------------------------------------------------------------------------ | -| **Name** | `workspace init` | -| **Description** | Initialize Bailian workspace and activate postpaid services | -| **Authentication** | No Auth | -| **Usage** | `bl workspace init --access-key-id --access-key-secret [--security-token ]` | +| Field | Value | +| ------------------ | ----------------------------------------------------------- | +| **Name** | `workspace init` | +| **Description** | Initialize Bailian workspace and activate postpaid services | +| **Authentication** | AK/SK | +| **Usage** | `bl workspace init [flags]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------ | ------ | -------- | ------------------------------------------- | -| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID | -| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret | -| `--security-token ` | string | no | Alibaba Cloud STS Security Token (optional) | +| Flag | Type | Required | Description | +| --------------------------- | ------ | -------- | ---------------------------------------------------------------------- | +| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID) | +| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET) | +| `--security-token ` | string | no | Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN) | #### Examples +```bash +bl workspace init +``` + ```bash bl workspace init --access-key-id LTAIxxxxx --access-key-secret xxxxx ``` From 954665b4000d27e2b46a1fcb43a63a9647a9178c Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Fri, 27 Nov 2026 19:00:17 +0800 Subject: [PATCH 02/13] fix(auth): harden OAuth session lifecycle and recovery Recover abandoned locks without rolling back committed credentials, keep route selection aligned with the actual credential, and protect sessions from concurrent logout. Cancel in-flight OAuth requests promptly and show only valid pre-release recovery steps. --- packages/commands/src/commands/auth/aliyun.ts | 13 +- .../commands/src/commands/auth/console-ui.ts | 3 +- packages/commands/src/commands/auth/logout.ts | 16 +- packages/commands/tests/auth-aliyun.test.ts | 141 ++++++++++---- packages/core/src/auth/aliyun-oauth.ts | 5 +- packages/core/src/auth/openapi-provider.ts | 14 +- packages/core/src/auth/refresh-token.ts | 6 +- packages/core/src/auth/store.ts | 39 ++-- packages/core/src/client/client.ts | 6 +- packages/core/src/console/gateway.ts | 5 +- packages/core/src/utils/file-lock.ts | 148 +++++++++------ packages/core/tests/openapi-provider.test.ts | 174 +++++++++++++++++- packages/runtime/src/create-cli.ts | 17 +- packages/runtime/src/error-handler.ts | 28 ++- packages/runtime/src/output/reporter.ts | 3 + .../tests/command-reference-output.test.ts | 103 ++++++++++- 16 files changed, 549 insertions(+), 172 deletions(-) diff --git a/packages/commands/src/commands/auth/aliyun.ts b/packages/commands/src/commands/auth/aliyun.ts index 6618254c4..14e720756 100644 --- a/packages/commands/src/commands/auth/aliyun.ts +++ b/packages/commands/src/commands/auth/aliyun.ts @@ -495,7 +495,7 @@ export async function runAliyunOAuthLogin( const onSignal = () => cancellation.abort(); const releaseInterrupt = registerInterruptHandler(onSignal); process.once("SIGTERM", onSignal); - const oauthDeps = { identity: deps.identity, timeout: deps.settings.timeout }; + const oauthDeps = { identity: deps.identity, timeout: deps.settings.timeout, signal }; const secrets: string[] = []; let session: AliyunOAuthSession | undefined; let saved = false; @@ -526,6 +526,7 @@ export async function runAliyunOAuthLogin( accessKeyId: session.sts.accessKeyId, accessKeySecret: session.sts.accessKeySecret, securityToken: session.sts.securityToken, + signal, }); secrets.push(cliAccessToken); assertActive(signal, deps); @@ -534,7 +535,7 @@ export async function runAliyunOAuthLogin( site: "domestic" as const, gateway: profile.console_gateway, }; - await validateConsoleAccessToken({ ...target, token: cliAccessToken }, settings); + await validateConsoleAccessToken({ ...target, token: cliAccessToken }, settings, { signal }); assertActive(signal, deps); // Console TTL is intentionally absent: GenerateCLIAccessToken has no confirmed TTL field. session.consoleTokens = { [consoleCredentialKey(target)]: { token: cliAccessToken } }; @@ -552,14 +553,16 @@ export async function runAliyunOAuthLogin( }, ); } catch (error) { + const cancelled = !saved && signal.aborted; if (!saved && session?.refreshToken) { - // Cleanup failure must not replace the exchange/validation/persistence error. + // Revoke only a known RT, with its own deadline. Never replay an uncertain code exchange. await revokeAliyunTokens(profile, session.refreshToken, { - ...oauthDeps, + identity: oauthDeps.identity, timeout: Math.min(oauthDeps.timeout, 5), }).catch(() => {}); } - throw safeLoginError(error, secrets); + // Cleanup must not replace the primary failure or expose the abort reason. + throw cancelled ? interrupted(deps) : safeLoginError(error, secrets); } finally { releaseInterrupt(); process.off("SIGTERM", onSignal); diff --git a/packages/commands/src/commands/auth/console-ui.ts b/packages/commands/src/commands/auth/console-ui.ts index fb7789658..71b385055 100644 --- a/packages/commands/src/commands/auth/console-ui.ts +++ b/packages/commands/src/commands/auth/console-ui.ts @@ -7,7 +7,6 @@ import { type Settings, } from "bailian-cli-core"; import { runConsoleLogin, resolveConsoleOrigin } from "./login-console.ts"; -import { logoutStoredAuth } from "./logout.ts"; /** Read-only auth snapshot the config UI account widget renders. bl stores no * user profile (name/avatar), so this exposes only which credential domains @@ -105,7 +104,7 @@ export function makeAuthUiBridge(ctx: { } }, logout() { - return logoutStoredAuth(authStore, "all", pre); + return authStore.logout("all"); }, }; } diff --git a/packages/commands/src/commands/auth/logout.ts b/packages/commands/src/commands/auth/logout.ts index 154586589..99df66fa6 100644 --- a/packages/commands/src/commands/auth/logout.ts +++ b/packages/commands/src/commands/auth/logout.ts @@ -1,16 +1,4 @@ -import { defineCommand, type AuthStore } from "bailian-cli-core"; - -type LogoutScope = Parameters[0]; - -export async function logoutStoredAuth(store: AuthStore, scope: LogoutScope, pre: boolean) { - if (!pre || scope !== "all") return store.logout(scope); - - // Use only the bound control-plane store and leave all model settings intact. - const clearedOAuth = await store.logout("aliyun"); - const clearedConsole = await store.logout("console"); - const clearedOpenApi = await store.logout("openapi"); - return clearedOAuth || clearedConsole || clearedOpenApi; -} +import { defineCommand } from "bailian-cli-core"; export default defineCommand({ description: { @@ -155,7 +143,7 @@ export default defineCommand({ ); return; } - const cleared = await logoutStoredAuth(store, scope, pre); + const cleared = await store.logout(scope); const lines = [ ...environmentLine, ctx.localize( diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index f2433ecd8..fca863103 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -49,7 +49,14 @@ const SECRETS = { securityToken: "test-sts-security-token-secret", cliAccessToken: "test-cli-access-token-secret", }; -type Stage = "token" | "sts" | "generate" | "gateway"; +const STAGES = ["token", "sts", "generate", "gateway"] as const; +type Stage = (typeof STAGES)[number]; +const STAGE_PATHS: Record = { + token: "/v1/token", + sts: "/v1/exchange", + generate: "/modelstudio/cli/generateAccessToken", + gateway: "/cli/api.json", +}; interface RecordedRequest { url: URL; init: RequestInit; @@ -57,6 +64,9 @@ interface RecordedRequest { let isolation: IsolatedHomeHandle; let requests: RecordedRequest[]; let failStage: Stage | undefined; +let pauseStage: + | { stage: Stage; hold: (signal: RequestInit["signal"]) => Promise } + | undefined; let revokeFails: boolean; let stsExpiresAt: number; let accessTokenIssuedAt: number; @@ -90,6 +100,7 @@ beforeEach(() => { requests = []; activeProbes = []; failStage = undefined; + pauseStage = undefined; revokeFails = false; stsExpiresAt = Date.now() + 3600_000; accessTokenIssuedAt = 0; @@ -121,6 +132,7 @@ beforeEach(() => { ) stage = "gateway"; else throw new Error(`Unexpected mocked endpoint: ${url.origin}${url.pathname}`); + if (pauseStage?.stage === stage) return pauseStage.hold(init.signal); if (stage === failStage) { if (stage === "gateway") return jsonResponse({ @@ -672,45 +684,99 @@ test("预先取消的信号在 proof/监听/浏览器/网络之前失败", async assertSignalCleanup(probe); }); -test.each(["token", "sts", "generate", "gateway"] as const)( - "%s下游失败不保存 Profile;已获得 RT 时尽力撤销且不泄漏凭据", - async (stage) => { - failStage = stage; - const probe = launch(); +test.each(STAGES)("%s 请求在途时 Ctrl+C 中止换票,仅撤销已获得的 RT", async (stage) => { + const started = deferred(); + const released = deferred(); + const timeout = vi.spyOn(AbortSignal, "timeout"); + revokeFails = stage === "gateway"; + pauseStage = { + stage, + async hold(signal) { + const onAbort = () => released.resolve(undefined); + signal?.addEventListener("abort", onAbort, { once: true }); + started.resolve(signal); + try { + await released.promise; + throw new DOMException(SECRETS.accessToken, "AbortError"); + } finally { + signal?.removeEventListener("abort", onAbort); + } + }, + }; + const probe = launch({ noBrowser: true }); + try { expect((await localRequest(callbackUrl(await probe.authUrl))).status).toBe(200); + const requestSignal = await Promise.race([ + started.promise, + probe.outcome.then(() => { + throw new Error("Login ended before the target request started"); + }), + ]); + expect(requestSignal?.aborted).toBe(false); + expect(timeout).toHaveBeenLastCalledWith(probe.deps.settings.timeout * 1000); + // Invoke the registered Ctrl+C handler without delivering an OS signal to the test worker. + Reflect.apply(process.listeners("SIGINT").at(-1)!, process, []); + expect(requestSignal?.aborted).toBe(true); + const error = await probe.outcome; - expect(error).toBeInstanceOf(BailianError); - expect(error).toMatchObject({ exitCode: ExitCode.GENERAL }); + expect(error).toMatchObject({ exitCode: ExitCode.INTERRUPTED }); + expect(probe.reporter.error(error)).toBe(130); expect(probe.save).not.toHaveBeenCalled(); expect(probe.stdout).toEqual([]); - const revocations = requests.filter((request) => request.url.pathname === "/v1/revoke"); - expect(revocations).toHaveLength(stage === "token" ? 0 : 1); + const expectedPaths = STAGES.slice(0, STAGES.indexOf(stage) + 1).map( + (requestStage) => STAGE_PATHS[requestStage], + ); if (stage !== "token") { - expect( - Object.fromEntries(new URLSearchParams(stringBody(revocations[0]!.init.body))), - ).toEqual({ client_id: ALIYUN_CLI_CLIENT_ID, token: SECRETS.refreshToken }); - expect(revocations[0]!.init.redirect).toBe("error"); + expectedPaths.push("/v1/revoke"); + const revoke = requests.at(-1)!; + expect(revoke.init.signal?.aborted).toBe(false); + expect(timeout).toHaveBeenLastCalledWith(5000); + expect(new URLSearchParams(stringBody(revoke.init.body)).get("token")).toBe( + SECRETS.refreshToken, + ); } - if (stage === "gateway") - expect(error).toMatchObject({ - api: { apiCode: "ValidationDenied", requestId: "mock-request-id" }, - }); - probe.reporter.error(error); - const requestPaths = [ - "/v1/token", - "/v1/exchange", - "/modelstudio/cli/generateAccessToken", - "/cli/api.json", - ]; - expect( - requests - .filter((request) => request.url.pathname !== "/v1/revoke") - .map((request) => request.url.pathname), - ).toEqual(requestPaths.slice(0, ["token", "sts", "generate", "gateway"].indexOf(stage) + 1)); + expect(requests.map(({ url }) => url.pathname)).toEqual(expectedPaths); assertNoSecrets(probe); assertSignalCleanup(probe); - }, -); + } finally { + // Unblock after a failed assertion even if a regression dropped cancellation from fetch. + released.resolve(undefined); + } +}); + +test.each(STAGES)("%s下游失败不保存 Profile;已获得 RT 时尽力撤销且不泄漏凭据", async (stage) => { + failStage = stage; + const probe = launch(); + expect((await localRequest(callbackUrl(await probe.authUrl))).status).toBe(200); + const error = await probe.outcome; + expect(error).toBeInstanceOf(BailianError); + expect(error).toMatchObject({ exitCode: ExitCode.GENERAL }); + expect(probe.save).not.toHaveBeenCalled(); + expect(probe.stdout).toEqual([]); + const revocations = requests.filter((request) => request.url.pathname === "/v1/revoke"); + expect(revocations).toHaveLength(stage === "token" ? 0 : 1); + if (stage !== "token") { + expect(Object.fromEntries(new URLSearchParams(stringBody(revocations[0]!.init.body)))).toEqual({ + client_id: ALIYUN_CLI_CLIENT_ID, + token: SECRETS.refreshToken, + }); + expect(revocations[0]!.init.redirect).toBe("error"); + } + if (stage === "gateway") + expect(error).toMatchObject({ + api: { apiCode: "ValidationDenied", requestId: "mock-request-id" }, + }); + probe.reporter.error(error); + expect( + requests + .filter((request) => request.url.pathname !== "/v1/revoke") + .map((request) => request.url.pathname), + ).toEqual( + STAGES.slice(0, STAGES.indexOf(stage) + 1).map((requestStage) => STAGE_PATHS[requestStage]), + ); + assertNoSecrets(probe); + assertSignalCleanup(probe); +}); test.each(["network", "timeout"] as const)( "传输%s错误保留 runtime 分类且脱敏 cause", @@ -775,6 +841,17 @@ test("下游阶段取消不保存,并撤销已经获得的 RT", async () => { assertSignalCleanup(probe); }); +test("已开始持久化时取消,不撤销成功保存的会话", async () => { + const probe = launch({ noBrowser: true }); + probe.save.mockImplementation(async () => probe.controller.abort()); + await finish(probe); + expect(probe.save).toHaveBeenCalledTimes(1); + expect(requests.map(({ url }) => url.pathname)).not.toContain("/v1/revoke"); + expect(JSON.parse(probe.stdout.join(""))).toMatchObject({ authenticated: true }); + assertNoSecrets(probe); + assertSignalCleanup(probe); +}); + test.each([false, true])( "既有 OAuth 端点优先于默认值,显式端点覆盖优先于 Profile (%s)", async (overrideEndpoints) => { diff --git a/packages/core/src/auth/aliyun-oauth.ts b/packages/core/src/auth/aliyun-oauth.ts index c2c23a03e..5f1930ae5 100644 --- a/packages/core/src/auth/aliyun-oauth.ts +++ b/packages/core/src/auth/aliyun-oauth.ts @@ -9,6 +9,8 @@ import type { AliyunOAuthProfile, AliyunOAuthTokens, AliyunOAuthSession } from " export interface AliyunOAuthDeps extends Pick { timeout: number; + /** Optional cancellation for token and STS exchanges. */ + signal?: AbortSignal; now?: () => number; warning?: HttpDeps["debug"]; recoveryHint?: string; @@ -68,12 +70,13 @@ async function postOAuth( ): Promise> { const endpoint = `${profile.oauth_base_url}${path}`; debugRequest(deps, "POST", endpoint); + const timeout = AbortSignal.timeout(deps.timeout * 1000); const response = await httpTransport.fetch(endpoint, { method: "POST", headers: { ...trackingHeaders(deps.identity), ...headers }, body, redirect: "error", - signal: AbortSignal.timeout(deps.timeout * 1000), + signal: deps.signal ? AbortSignal.any([deps.signal, timeout]) : timeout, }); debugResponse(deps, response); const raw = await response.text(); diff --git a/packages/core/src/auth/openapi-provider.ts b/packages/core/src/auth/openapi-provider.ts index cb0dd7334..4f7d7326d 100644 --- a/packages/core/src/auth/openapi-provider.ts +++ b/packages/core/src/auth/openapi-provider.ts @@ -284,14 +284,11 @@ export function createOpenApiCredentialProvider( if (!selectedOAuth(boundSources, purpose)) staticCredential(boundSources); }, resolveConsoleTarget(target, purpose = "console") { - const profile = currentSources().file.aliyun_oauth; - const active = profile?.[purpose === "console" ? "console_enabled" : "openapi_enabled"]; - if (profile && active) validateTarget(profile, target); + const profile = selectedOAuth(currentSources(), purpose); + if (profile) validateTarget(profile, target); const gateway = pre ? requirePreConsoleGateway(pre, target) - : profile && active - ? profile.console_gateway - : target.gateway; + : (profile?.console_gateway ?? target.gateway); return { region: target.region, site: target.site, @@ -300,11 +297,10 @@ export function createOpenApiCredentialProvider( }; }, resolveHost(host, credential, purpose = "openapi") { - const profile = currentSources().file.aliyun_oauth; + const profile = selectedOAuth(currentSources(), purpose); if ( credential?.method === "aliyun-oauth" && (!profile || - !profile[purpose === "console" ? "console_enabled" : "openapi_enabled"] || profile.session_ref !== credential.sessionRef || credential.configurationFingerprint !== oauthConfigurationFingerprint(profile)) ) @@ -313,7 +309,7 @@ export function createOpenApiCredentialProvider( "The OAuth login changed or was removed. / OAuth 登录已变更或被移除。", ); if (pre) return resolvePreOpenApiHost(host); - if (!profile?.[purpose === "console" ? "console_enabled" : "openapi_enabled"]) return host; + if (!profile || (credential && credential.method !== "aliyun-oauth")) return host; if ( /^modelstudio(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host) || host === profile.modelstudio_host diff --git a/packages/core/src/auth/refresh-token.ts b/packages/core/src/auth/refresh-token.ts index f0a9b8401..9e30b9a47 100644 --- a/packages/core/src/auth/refresh-token.ts +++ b/packages/core/src/auth/refresh-token.ts @@ -67,13 +67,13 @@ export function resolveCLIAccessTokenTarget( export async function validateConsoleAccessToken( target: ConsoleGatewayTarget, settings: Settings, - diagnostics: Pick = {}, + options: Pick & { signal?: AbortSignal } = {}, ): Promise { const response = (await callConsoleGateway( target, settings.timeout, { api: "zeldaEasy.cornerstone-portal.cs-console.loginInfo", data: {} }, - { ...diagnostics, preControlPlane: settings.preControlPlane }, + { ...options, preControlPlane: settings.preControlPlane }, )) as { data?: { success?: boolean } } | null; if (response?.data?.success !== true) { throw new BailianError( @@ -91,6 +91,7 @@ export type GenerateCLIAccessTokenOptions = { debug?: HttpDeps["debug"]; baseUrl: string; modelStudioHost?: string; + signal?: AbortSignal; } & ( | { client: Client; accessKeyId?: never; accessKeySecret?: never; securityToken?: never } | { @@ -129,6 +130,7 @@ export async function generateCLIAccessToken(opts: GenerateCLIAccessTokenOptions version: API_VERSION, method: "POST", queryParams: {}, + signal: opts.signal, }); if (typeof response.cliAccessToken !== "string" || !response.cliAccessToken.trim()) { throw new BailianError( diff --git a/packages/core/src/auth/store.ts b/packages/core/src/auth/store.ts index f1681fa4f..35aa95965 100644 --- a/packages/core/src/auth/store.ts +++ b/packages/core/src/auth/store.ts @@ -217,15 +217,23 @@ export function makeAuthStore( }, async logout(scope) { const profile = readBoundConfig().aliyun_oauth; - const clearConfig = async (reference?: string, removeOAuth = false) => { - let cleared = false; - await mutateConfigFile( + const reference = profile?.session_ref; + const removeOAuth = scope === "all" || scope === "aliyun"; + const keys = + pre && scope === "all" + ? [...LOGOUT_KEYS.console, ...LOGOUT_KEYS.openapi] + : LOGOUT_KEYS[scope]; + const changedSession = () => + new CredentialError( + "changed-openapi-identity", + "The OAuth login changed during logout. / 退出期间 OAuth 登录已变更。", + ); + const clearConfig = () => + mutateConfigFile( (current) => { - if (reference && current.aliyun_oauth?.session_ref !== reference) return undefined; + if (current.aliyun_oauth?.session_ref !== reference) throw changedSession(); + if (!reference && !keys.some((key) => current[key] !== undefined)) return undefined; const existing = { ...current }; - const keys = LOGOUT_KEYS[scope]; - cleared = keys.some((key) => existing[key] !== undefined) || Boolean(reference); - if (!cleared) return undefined; for (const key of keys) delete existing[key]; if (removeOAuth) delete existing.aliyun_oauth; else if (existing.aliyun_oauth) @@ -239,39 +247,34 @@ export function makeAuthStore( configName, { path: configurationPath }, ); - return cleared; - }; - if (!profile) return clearConfig(); + if (!profile || scope === "openapi") return clearConfig(); return withFileLock(oauthSessionLockPath(directory, profile.session_ref), async () => { const current = readBoundConfig().aliyun_oauth; - if (current?.session_ref !== profile.session_ref) return false; + if (current?.session_ref !== profile.session_ref) throw changedSession(); if (pre) validatePreAliyunProfile(current); - const removeOAuth = scope === "all" || scope === "aliyun"; const raw = await getSecretStore().read(profile.session_ref); if (removeOAuth) { if (raw) { const session = parseOAuthSession(raw); - assertOAuthConfiguration(profile, session); + assertOAuthConfiguration(current, session); if (session.refreshToken) { if (!oauthDeps) throw new CredentialError( "missing-aliyun-session", "OAuth logout requires OAuth transport dependencies. / OAuth 退出需要 OAuth 传输配置。", ); - await revokeAliyunTokens(profile, session.refreshToken, oauthDeps); + await revokeAliyunTokens(current, session.refreshToken, oauthDeps); } } await getSecretStore().remove(profile.session_ref); - return clearConfig(profile.session_ref, true); - } - if (scope === "console" && raw) { + } else if (raw) { const session = parseOAuthSession(raw); await getSecretStore().write( profile.session_ref, JSON.stringify({ ...session, consoleTokens: {} }), ); } - return clearConfig(profile.session_ref); + return clearConfig(); }); }, get path() { diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index f55bef61d..c20973a99 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -60,6 +60,7 @@ export interface ClientOpenApiQueryOpts { version: string; method: "GET" | "POST"; queryParams: AcsQueryParams; + signal?: AbortSignal; } export interface ClientOpenApiJsonOpts { @@ -71,6 +72,7 @@ export interface ClientOpenApiJsonOpts { /** JSON request body; omit for query-only calls (signed as an empty body). */ body?: unknown; queryParams?: AcsQueryParams; + signal?: AbortSignal; } export interface OpenApiResponse { @@ -395,13 +397,13 @@ export class Client { this.recordRequest(endpoint); debugRequest(this.http, opts.method, endpoint, { action: opts.action, version: opts.version }); - const timeoutMs = this.deps.settings.timeout * 1000; + const timeout = AbortSignal.timeout(this.deps.settings.timeout * 1000); const res = await httpTransport.fetch(endpoint, { method: opts.method, headers: { ...headers, ...trackingHeaders(this.deps.identity) }, body: bodyStr || undefined, redirect: "error", - signal: AbortSignal.timeout(timeoutMs), + signal: opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout, }); const rawText = await res.text(); diff --git a/packages/core/src/console/gateway.ts b/packages/core/src/console/gateway.ts index 1c8ab8fa2..184c317a6 100644 --- a/packages/core/src/console/gateway.ts +++ b/packages/core/src/console/gateway.ts @@ -165,6 +165,7 @@ export async function callConsoleGateway( options: Pick & { recoveryHint?: string; preControlPlane?: PreControlPlane; + signal?: AbortSignal; } = {}, ): Promise { const resolved = resolveGateway(target.region, target.site); @@ -181,7 +182,6 @@ export async function callConsoleGateway( const params = buildGatewayParams(api, data, target.switchAgent); const body = new URLSearchParams({ params, region: target.region }); - const timeoutMs = timeoutSec * 1000; const headers: Record = { Accept: "*/*", @@ -192,12 +192,13 @@ export async function callConsoleGateway( const endpoint = `${gatewayBase}/cli/api.json?action=${action}&product=${GATEWAY_PRODUCT}&api=${encodeURIComponent(api)}`; debugRequest(options, "POST", endpoint, { api, region: target.region }); + const timeout = AbortSignal.timeout(timeoutSec * 1000); const res = await httpTransport.fetch(endpoint, { method: "POST", headers, body: body.toString(), ...(pre || target.gateway ? { redirect: "error" as const } : {}), - signal: AbortSignal.timeout(timeoutMs), + signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout, }); debugResponse(options, res); diff --git a/packages/core/src/utils/file-lock.ts b/packages/core/src/utils/file-lock.ts index 98044ee1a..2513bcc60 100644 --- a/packages/core/src/utils/file-lock.ts +++ b/packages/core/src/utils/file-lock.ts @@ -1,81 +1,107 @@ import { randomUUID } from "node:crypto"; -import { mkdir, open, readFile, unlink } from "node:fs/promises"; -import { dirname } from "node:path"; +import { + lstat, + mkdir, + mkdtemp, + readdir, + readFile, + rename, + rm, + rmdir, + unlink, + writeFile, +} from "node:fs/promises"; +import { dirname, join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; +const OWNER_NAME = /^owner-([1-9]\d*)-[a-f0-9-]{36}$/u; +const CONTENTION_CODES = new Set(["EEXIST", "ENOTEMPTY", "ENOTDIR", "EISDIR"]); + +function ownerAlive(pid: unknown): boolean { + if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || pid > 0x7fff_ffff) + return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code !== "ESRCH"; + } +} + +async function releaseLock(path: string, owner?: string): Promise { + // Only the matching marker can be removed; rmdir never removes a replacement lock with a live owner. + if (owner) await unlink(join(path, owner)).catch(() => {}); + await rmdir(path).catch(() => {}); +} + +async function recoverLock(path: string): Promise { + const status = await lstat(path).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") throw error; + }); + if (status?.isFile()) { + const previous = await readFile(path, "utf8").catch(() => undefined); + if (previous === undefined) return; + let pid: unknown; + try { + pid = (JSON.parse(previous) as { pid?: unknown } | null)?.pid; + } catch { + // Leave a grace period for an older process still publishing its ownership record. + if (Date.now() - status.mtimeMs < 1_000) return; + } + if (!ownerAlive(pid)) await unlink(path).catch(() => {}); + return; + } + if (!status?.isDirectory()) return; + const entries = await readdir(path).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") throw error; + }); + if (entries?.length === 0) await releaseLock(path); + else if (entries?.length === 1) { + const owner = entries[0]!; + const match = OWNER_NAME.exec(owner); + if (match && !ownerAlive(Number(match[1]))) await releaseLock(path, owner); + } +} + export async function withFileLock( path: string, operation: () => Promise, timeout = 30_000, ): Promise { await mkdir(dirname(path), { recursive: true, mode: 0o700 }); - const ownership = JSON.stringify({ pid: process.pid, id: randomUUID() }); + const candidate = await mkdtemp(`${path}.`); + const owner = `owner-${process.pid}-${randomUUID()}`; + let acquired = false; const deadline = Date.now() + timeout; - for (;;) { - try { - const handle = await open(path, "wx", 0o600); - try { - await handle.writeFile(ownership); - } finally { - await handle.close(); - } - break; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; - const previous = await readFile(path, "utf8").catch((readError: NodeJS.ErrnoException) => { - if (readError.code === "ENOENT") return undefined; - throw readError; - }); - if (previous === undefined) continue; - let owner: { pid?: unknown } = {}; + try { + await writeFile(join(candidate, owner), "", { mode: 0o600 }); + for (;;) { try { - owner = JSON.parse(previous); - } catch { - // A live writer may not have finished writing its ownership record. - } - if (typeof owner.pid === "number" && Number.isInteger(owner.pid) && owner.pid > 0) { - try { - process.kill(owner.pid, 0); - } catch (ownerError) { - if ((ownerError as NodeJS.ErrnoException).code === "ESRCH") { - const recoveryPath = `${path}.recovery`; - const recovery = await open(recoveryPath, "wx", 0o600).catch( - (recoveryError: NodeJS.ErrnoException) => { - if (recoveryError.code === "EEXIST") return undefined; - throw recoveryError; - }, - ); - if (recovery) { - try { - if ((await readFile(path, "utf8").catch(() => undefined)) === previous) { - await unlink(path).catch((removeError: NodeJS.ErrnoException) => { - if (removeError.code !== "ENOENT") throw removeError; - }); - } - } finally { - await recovery.close(); - await unlink(recoveryPath); - } - } - } + // Publish a nonempty directory atomically; rename cannot replace another owner's nonempty lock. + await rename(candidate, path); + acquired = true; + break; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + const windowsCollision = + process.platform === "win32" && (code === "EPERM" || code === "EACCES"); + if (!CONTENTION_CODES.has(code ?? "") && !windowsCollision) throw error; + await recoverLock(path); + if (Date.now() >= deadline) { + throw new BailianError( + "Timed out waiting for the credential/configuration lock. / 等待凭据或配置锁超时。", + ExitCode.TIMEOUT, + ); } + await delay(25); } - if (Date.now() >= deadline) { - throw new BailianError( - "Timed out waiting for the credential/configuration lock. / 等待凭据或配置锁超时。", - ExitCode.TIMEOUT, - ); - } - await delay(25); } - } - try { return await operation(); } finally { - if ((await readFile(path, "utf8").catch(() => undefined)) === ownership) { - await unlink(path); - } + // A cleanup error must not make a committed operation look like a failed write. + if (acquired) await releaseLock(path, owner); + else await rm(candidate, { recursive: true, force: true }).catch(() => {}); } } diff --git a/packages/core/tests/openapi-provider.test.ts b/packages/core/tests/openapi-provider.test.ts index abb558bdc..e1b86af99 100644 --- a/packages/core/tests/openapi-provider.test.ts +++ b/packages/core/tests/openapi-provider.test.ts @@ -1,5 +1,6 @@ import { spawn, type ChildProcess } from "node:child_process"; -import { readFile, readdir, writeFile } from "node:fs/promises"; +import files, { mkdir, readFile, readdir, utimes, writeFile } from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { @@ -14,6 +15,7 @@ import { import type { AliyunOAuthDeps } from "../src/auth/aliyun-oauth.ts"; import type { AliyunOAuthProfile, AliyunOAuthSession } from "../src/auth/aliyun-types.ts"; import { + bindOpenApiConsoleCredentials, consoleCredentialKey, createOpenApiCredentialProvider, oauthConfigurationFingerprint, @@ -39,6 +41,7 @@ import { import type { ConfigFile } from "../src/config/schema.ts"; import { BailianError, UsageError } from "../src/errors/base.ts"; import { CredentialError } from "../src/errors/credential.ts"; +import { withFileLock } from "../src/utils/file-lock.ts"; import { enterIsolatedHome, type IsolatedHomeHandle } from "./helpers/isolation.ts"; const NOW = Date.UTC(2026, 0, 1); @@ -252,7 +255,12 @@ describe("pre-release control-plane isolation", () => { CredentialError, ); const auth = makeAuthStore(sources, deps); - await auth.login({ access_key_id: "pre-ak", access_key_secret: "pre-sk" }); + await auth.login({ + access_key_id: "pre-ak", + access_key_secret: "pre-sk", + api_key: MODEL_KEY, + base_url: "https://model.example.test", + }); const preFile = JSON.parse(await readFile(auth.path, "utf8")); expect(preFile).toMatchObject({ control_environment: "pre", active_config: "team" }); const markerCopy = join(isolation.configDir, "copied-online.json"); @@ -263,6 +271,9 @@ describe("pre-release control-plane isolation", () => { expect(selected.file.access_key_id).toBe("pre-ak"); expect(buildSources({ config: "default" }, undefined, pre).file.access_key_id).toBeUndefined(); expect(await auth.logout("all")).toBe(true); + const remaining = readConfigFile("team", auth.path); + expect(remaining).toMatchObject({ api_key: MODEL_KEY, base_url: "https://model.example.test" }); + expect(remaining.access_key_id).toBeUndefined(); expect(readConfigFile("team", onlinePath).access_key_id).toBe("online-ak"); expect(transport).not.toHaveBeenCalled(); }); @@ -976,6 +987,82 @@ describe("Console cache and endpoint isolation", () => { expect(() => instance.provider.resolveHost("bailiancontrol.aliyuncs.com")).toThrow(UsageError); expect(transport).not.toHaveBeenCalled(); }); + + test.each([ + { flags: { accessKeyId: "fixture-override-id", accessKeySecret: "fixture-override-secret" } }, + { + env: { + BAILIAN_ACCESS_KEY_ID: "fixture-override-id", + BAILIAN_ACCESS_KEY_SECRET: "fixture-override-secret", + }, + }, + ])( + "static overrides use ordinary OpenAPI and Console routes for an OAuth Profile (%#)", + async (overrides) => { + const instance = await setup({ + ...overrides, + file: { aliyun_oauth: profile({ bailiancontrol_host: undefined }) }, + }); + const provider = bindOpenApiConsoleCredentials(instance.provider); + const host = "bailiancontrol.cn-beijing.aliyuncs.com"; + const client = new Client({ + identity: deps.identity, + settings: buildSettings(instance.sources), + baseUrl: "https://dashscope.aliyuncs.com", + openApiProvider: provider, + }); + expect(client.resolveOpenApiHost(host)).toBe(host); + expect(provider.resolveConsoleTarget(TARGET)).toEqual(TARGET); + expect(provider.resolveHost("modelstudio.aliyuncs.com")).toBe("modelstudio.aliyuncs.com"); + expect(transport).not.toHaveBeenCalled(); + transport.mockResolvedValueOnce(json({ Success: true })); + await client.openApiJson({ + host, + path: "/readonly", + action: "ListFixture", + version: "2026-01-01", + method: "GET", + }); + const [endpoint, options] = transport.mock.calls[0]!; + expect(endpoint).toBe(`https://${host}/readonly`); + expect(new Headers(options?.headers).get("authorization")).toContain( + "Credential=fixture-override-id", + ); + expect(instance.store.read).not.toHaveBeenCalled(); + }, + ); +}); + +describe("credential and configuration lock recovery", () => { + test.each(["", '{"pid":'])("recovers a stale incomplete lock record %j", async (record) => { + const path = join(isolation.configDir, "config.json.lock"); + await writeFile(path, record); + await writeFile(`${path}.recovery`, ""); + const stale = new Date(Date.now() - 5_000); + await utimes(path, stale, stale); + await expect(withFileLock(path, async () => true, 500)).resolves.toBe(true); + await expect(readFile(path)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + test.each(["empty", "dead owner"] as const)( + "recovers a lock directory left with %s", + async (state) => { + const path = join(isolation.configDir, "config.json.lock"); + await mkdir(path); + if (state === "dead owner") { + const pid = 987654; + await writeFile(join(path, `owner-${pid}-${REFERENCE}`), ""); + const kill = process.kill.bind(process); + vi.spyOn(process, "kill").mockImplementation((target, signal) => { + if (target === pid && signal === 0) + throw Object.assign(new Error("No such process"), { code: "ESRCH" }); + return kill(target, signal); + }); + } + await expect(withFileLock(path, async () => true, 500)).resolves.toBe(true); + await expect(readdir(path)).rejects.toMatchObject({ code: "ENOENT" }); + }, + ); }); describe("Profile references, login and domain-specific logout", () => { @@ -1053,6 +1140,29 @@ describe("Profile references, login and domain-specific logout", () => { expect(instance.store.remove).not.toHaveBeenCalled(); }); + test("a config lock cleanup failure after login does not delete the committed session", async () => { + const instance = await setup(); + const lockPath = `${instance.sources.configPath!}.lock`; + const removeDirectory = files.rmdir; + const cleanup = vi.spyOn(files, "rmdir").mockImplementation(async (...args) => { + if (args[0] === lockPath) + throw Object.assign(new Error("Cannot remove lock directory"), { code: "EACCES" }); + return removeDirectory(...args); + }); + syncBuiltinESMExports(); + try { + await instance.auth.loginAliyun(profile(), session()); + expect(cleanup).toHaveBeenCalledWith(lockPath); + const reference = readConfigFile().aliyun_oauth!.session_ref; + expect(reference).not.toBe(REFERENCE); + expect(instance.values.has(reference)).toBe(true); + } finally { + cleanup.mockRestore(); + syncBuiltinESMExports(); + } + expect(await instance.auth.logout("openapi")).toBe(true); + }); + test("relogin uses a new reference and invalidates credentials held by the old provider", async () => { const instance = await setup({ oauthSession: session({ sts: sts() }) }); const previous = await instance.provider.getCredential(); @@ -1218,6 +1328,52 @@ describe("Profile references, login and domain-specific logout", () => { }, ); + test("OpenAPI logout clears static keys and disables only OpenAPI without reading a damaged OAuth file", async () => { + const instance = await setup({ + file: { + aliyun_oauth: profile(), + access_key_id: "fixture-static-id", + access_key_secret: "fixture-static-secret", + }, + }); + instance.store.read.mockRejectedValue(new Error("OAuth file is unreadable")); + expect(await instance.auth.logout("openapi")).toBe(true); + const file = readConfigFile(); + expect(file.access_key_id).toBeUndefined(); + expect(file.access_key_secret).toBeUndefined(); + expect(file.aliyun_oauth).toMatchObject({ + session_ref: REFERENCE, + openapi_enabled: false, + console_enabled: true, + }); + expect(instance.store.read).not.toHaveBeenCalled(); + expect(instance.store.remove).not.toHaveBeenCalled(); + }); + + test("full logout rejects a concurrently created OAuth session instead of deleting its reference", async () => { + const instance = await setup({ file: { access_token: "fixture-static-console" } }); + const configPath = instance.sources.configPath!; + const ready = deferred(); + const publish = deferred(); + const writing = withFileLock(`${configPath}.lock`, async () => { + ready.resolve(); + await publish.promise; + instance.values.set(REFERENCE, JSON.stringify(session())); + await writeFile(configPath, JSON.stringify({ aliyun_oauth: profile() })); + }); + await ready.promise; + const logout = expect(instance.auth.logout("all")).rejects.toMatchObject({ + reason: "changed-openapi-identity", + }); + publish.resolve(); + await writing; + await logout; + expect(readConfigFile().aliyun_oauth?.session_ref).toBe(REFERENCE); + expect(instance.values.has(REFERENCE)).toBe(true); + expect(instance.store.remove).not.toHaveBeenCalled(); + expect(transport).not.toHaveBeenCalled(); + }); + test("all logout clears every credential, while preserving unrelated settings and other profiles", async () => { const instance = await setup({ file: { @@ -1275,13 +1431,11 @@ function startLockContender(sources: ResolutionSources, fakeFile: string): Fixtu const directory = ${JSON.stringify(isolation.configDir)}; const fakeFile = ${JSON.stringify(fakeFile)}; const lockPath = oauthSessionLockPath(directory, sources.file.aliyun_oauth.session_ref); - const actualOpen = files.open; - files.open = async (...args) => { - try { return await actualOpen(...args); } - catch (error) { - if (String(args[0]) === lockPath && error.code === 'EEXIST') process.send({ type: 'contended' }); - throw error; - } + const actualReadDir = files.readdir; + files.readdir = async (...args) => { + const entries = await actualReadDir(...args); + if (String(args[0]) === lockPath && entries.length) process.send({ type: 'contended' }); + return entries; }; syncBuiltinESMExports(); httpTransport.fetch = async () => { throw new Error('A second process must reuse durable STS, not replay RT'); }; @@ -1438,7 +1592,7 @@ describe("OAuth credential binding regressions", () => { describe("cross-process OAuth session serialization", () => { test("a real child waits on the shared session lock and reuses the parent's rotated session without RT replay", async () => { // Necessary process boundary: a per-provider single-flight Map cannot protect a second CLI process. - // One parent/child pair exercises the actual EEXIST lock path and durable refresh recovery; + // One parent/child pair exercises the real lock contention and reuse of durable refresh results; // the on-disk store contains only synthetic fixture JSON, never an OS key or real credentials. const instance = await setup({ oauthSession: session({ accessTokenExpiresAt: NOW }) }); const fakeFile = join(isolation.configDir, "fixture-session.json"); diff --git a/packages/runtime/src/create-cli.ts b/packages/runtime/src/create-cli.ts index 050bdddc3..7c398d3f9 100644 --- a/packages/runtime/src/create-cli.ts +++ b/packages/runtime/src/create-cli.ts @@ -477,12 +477,14 @@ export function createCli(commands: Record, opts: CliOptions const localize = (text: LocalizedText) => translator.localize(text); const initialSettings = buildOutputSettings({ flags, env: process.env }); let outputFormat: "text" | "json" = initialSettings.output; - let reporter = createOutputReporter({ - settings: initialSettings, + let preControlPlane: PreControlPlane | undefined; + const reporterOptions = { localize, commandPrefix, hasCommand, - }); + isPreControlPlane: () => preControlPlane !== undefined, + }; + let reporter = createOutputReporter({ ...reporterOptions, settings: initialSettings }); const warnings: OutputDiagnostic[] = []; const cleanup = installProcessHandlers( () => reporter, @@ -490,7 +492,6 @@ export function createCli(commands: Record, opts: CliOptions () => outputFormat, ); try { - let preControlPlane: PreControlPlane | undefined; let controlPlaneError: UsageError | undefined; try { preControlPlane = opts.preControlPlane?.(); @@ -536,10 +537,8 @@ export function createCli(commands: Record, opts: CliOptions const sourceSettings = buildOutputSettings(sources); outputFormat = sourceSettings.output; reporter = createOutputReporter({ + ...reporterOptions, settings: sourceSettings, - localize, - commandPrefix, - hasCommand, configName: recoveryConfigName, }); setupProxyFromEnv(); @@ -556,10 +555,8 @@ export function createCli(commands: Record, opts: CliOptions (settings) => { outputFormat = settings.output; reporter = createOutputReporter({ + ...reporterOptions, settings, - localize, - commandPrefix, - hasCommand, configName: recoveryConfigName, }); for (const warning of warnings.splice(0)) reporter.output.warning(warning); diff --git a/packages/runtime/src/error-handler.ts b/packages/runtime/src/error-handler.ts index 2844b92ab..dda772f41 100644 --- a/packages/runtime/src/error-handler.ts +++ b/packages/runtime/src/error-handler.ts @@ -91,6 +91,8 @@ export interface ErrorHintOptions { * Implicit default is undefined; explicit `--config default` is `"default"`. */ configName?: string; + /** Pre-release mode resolved by the hosting CLI for this invocation. */ + preControlPlane?: boolean; } /** Detect AllocationQuota.FreeTierOnly without matching TPS/TPM insufficient_quota. */ @@ -158,9 +160,29 @@ export function errorHint( case "expired-console-session": return consoleRecoveryHint(commandPrefix, configName); case "missing-openapi-pair": - 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 `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-config": { + const loginWithPair = + "auth login --open-api --access-key-id --access-key-secret "; + if (options.preControlPlane) { + const passPair = localize({ + "en-US": + "Keep pre-release mode enabled. If the command accepts AccessKey flags, pass both `--access-key-id` and `--access-key-secret`.", + "zh-CN": + "请保持预发模式开启。如果命令支持 AccessKey 参数,请同时传入 `--access-key-id` 和 `--access-key-secret`。", + }); + if (!options.hasCommand?.("auth login")) return passPair; + const login = recoveryCommand(commandPrefix, loginWithPair, configName); + return `${passPair} ${localize({ + "en-US": `To save the pair, run \`${login}\`.`, + "zh-CN": `如需保存这对凭据,请运行 \`${login}\`。`, + })}`; + } + const guide = recoveryCommand(commandPrefix, "auth login --open-api", configName); + if (error.reason === "missing-openapi-pair") { + return `Set BAILIAN_ACCESS_KEY_ID / BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_*), pass --access-key-id / --access-key-secret, or run \`${guide}\` then paste your AccessKey.`; + } + return `Save a complete pair with \`${recoveryCommand(commandPrefix, loginWithPair, configName)}\`, or run \`${guide}\` for the setup guide.`; + } case "incomplete-openapi-flag": case "incomplete-openapi-env": return hint; diff --git a/packages/runtime/src/output/reporter.ts b/packages/runtime/src/output/reporter.ts index eef087761..574861f73 100644 --- a/packages/runtime/src/output/reporter.ts +++ b/packages/runtime/src/output/reporter.ts @@ -27,6 +27,8 @@ export interface OutputReporterOptions { hasCommand?: (path: string) => boolean; /** Profile pinned in recovery hints (via resolveRecoveryConfigName). */ configName?: string; + /** Read the invocation's pre-release mode, which may be resolved after reporter creation. */ + isPreControlPlane?: () => boolean; } export interface OutputReporter { @@ -114,6 +116,7 @@ export function createOutputReporter(options: OutputReporterOptions): OutputRepo const hint = errorHint(failure, options.commandPrefix ?? "cli", localize, { hasCommand: options.hasCommand, configName: recoveryConfigName, + preControlPlane: options.isPreControlPlane?.(), }); if (verbose && error instanceof Error && !(error instanceof BailianError)) { diagnostic("debug", { diff --git a/packages/runtime/tests/command-reference-output.test.ts b/packages/runtime/tests/command-reference-output.test.ts index 9500df1fd..bee8d2d55 100644 --- a/packages/runtime/tests/command-reference-output.test.ts +++ b/packages/runtime/tests/command-reference-output.test.ts @@ -1,9 +1,14 @@ -import { withIsolatedHome } from "e2e/isolation"; +import { buildIsolatedCliEnv, withIsolatedHome } from "e2e/isolation"; +import { runInProcess } from "e2e/in-process"; import { authStage, type RunContext } from "../src/middleware.ts"; import { expect, test, vi } from "vite-plus/test"; import { BailianError, CredentialError, + defineCommand, + getConfigPath, + resolvePreControlPlane, + writeConfigFile, resolveApiKey, resolveOpenApi, httpTransport, @@ -14,6 +19,7 @@ import { type LocalizedText, } from "bailian-cli-core"; import { createOutputReporter } from "../src/output/reporter.ts"; +import { createCli } from "../src/create-cli.ts"; function render(error: unknown, output: "text" | "json") { let stderr = ""; @@ -137,6 +143,101 @@ test.each(["bl", "aliyun bl"])( }, ); +test.each([ + { + label: "pre-release missing pair", + binName: "bl", + mode: "true", + preProfile: { name: "staging", language: "en-US" }, + }, + { + label: "pre-release incomplete config", + binName: "bl", + mode: "1", + preProfile: { name: "default", language: "zh-CN", access_key_id: "fixture-partial-id" }, + }, + { label: "online mode explicitly selected", binName: "bl", mode: "0" }, + { label: "kscli host has no mode switch", binName: "kscli", mode: "1" }, +])("CLI recovery respects the host's control-plane mode: $label", async (scenario) => { + const { binName, mode, preProfile } = scenario; + const args = ["probe", "--output", "json"]; + if (preProfile) args.push("--config", preProfile.name); + const run = vi.fn(async () => {}); + const probe = defineCommand({ auth: "openapi", description: "OpenAPI fixture", run }); + const login = defineCommand({ auth: "none", description: "Login fixture", async run() {} }); + const cli = createCli(binName === "bl" ? { probe, "auth login": login } : { probe }, { + binName, + clientName: "test", + npmPackage: "test", + version: "0.0.0", + ...(binName === "bl" ? { preControlPlane: () => resolvePreControlPlane(process.env) } : {}), + }); + const isolated = buildIsolatedCliEnv({ + overrides: { + BAILIAN_PRE: mode, + BAILIAN_PRE_CONSOLE_ORIGIN: undefined, + BAILIAN_PRE_CONSOLE_GATEWAY: undefined, + BAILIAN_ACCESS_KEY_ID: preProfile ? "fixture-bailian-id" : undefined, + BAILIAN_ACCESS_KEY_SECRET: preProfile ? "fixture-bailian-secret" : undefined, + ALIBABA_CLOUD_ACCESS_KEY_ID: preProfile ? "fixture-cloud-id" : undefined, + ALIBABA_CLOUD_ACCESS_KEY_SECRET: preProfile ? "fixture-cloud-secret" : undefined, + DASHSCOPE_VERBOSE: "0", + HTTP_PROXY: "", + HTTPS_PROXY: "", + NO_UPDATE_NOTIFIER: "1", + }, + }); + try { + const result = await runInProcess( + async () => { + if (preProfile) { + const { name, ...file } = preProfile; + await writeConfigFile(file, name === "default" ? undefined : name, { + path: getConfigPath({}), + }); + } + await cli.run(args); + }, + args, + { env: isolated.env }, + ); + expect(result.exitCode).toBe(ExitCode.AUTH); + expect(result.stdout).toBe(""); + expect(run).not.toHaveBeenCalled(); + const { message, hint } = JSON.parse(result.stderr).error; + expect(message).toBe( + preProfile?.access_key_id + ? "Incomplete OpenAPI AK/SK credentials found." + : "No OpenAPI AK/SK credentials found.", + ); + if (preProfile) { + expect(hint).toContain( + preProfile.language === "zh-CN" + ? "请保持预发模式开启。如果命令支持 AccessKey 参数,请同时传入" + : "Keep pre-release mode enabled. If the command accepts AccessKey flags, pass both", + ); + expect(hint).toContain("`--access-key-id`"); + expect(hint).toContain("`--access-key-secret`"); + const login = `bl auth login --open-api --access-key-id --access-key-secret --config ${preProfile.name}`; + expect(hint).toContain( + preProfile.language === "zh-CN" + ? `如需保存这对凭据,请运行 \`${login}\`。` + : `To save the pair, run \`${login}\`.`, + ); + expect(hint).not.toMatch( + /BAILIAN_ACCESS_KEY_|ALIBABA_CLOUD_|auth login --open-api(?: --config [\w-]+)?`/u, + ); + expect(result.stderr).not.toContain("fixture-"); + } else { + expect(hint).toBe( + `Set BAILIAN_ACCESS_KEY_ID / BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_*), pass --access-key-id / --access-key-secret, or run \`${binName} auth login --open-api\` then paste your AccessKey.`, + ); + } + } finally { + isolated.dispose(); + } +}); + test("Console errors carry complete hints before ordinary business wrapping", async () => { await withIsolatedHome(async () => { const response = { data: { success: false, errorCode: "BailianGateway.Login.NotLogined" } }; From 24c2156895e086e3b6ed5d5bb416ccc53a50f8ec Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Fri, 27 Nov 2026 19:21:45 +0800 Subject: [PATCH 03/13] fix(auth): pin Console retries to the original OAuth session Stop retries when their credential binding changes, including while a new token is in flight. Preserve legacy lock files rather than risking removal of a lock owned by an older writer. --- packages/core/src/auth/openapi-provider.ts | 28 ++-- packages/core/src/client/console-session.ts | 31 ++++- packages/core/src/utils/file-lock.ts | 23 ++-- packages/core/tests/openapi-provider.test.ts | 133 +++++++++++++++++-- 4 files changed, 178 insertions(+), 37 deletions(-) diff --git a/packages/core/src/auth/openapi-provider.ts b/packages/core/src/auth/openapi-provider.ts index 4f7d7326d..68316c1e1 100644 --- a/packages/core/src/auth/openapi-provider.ts +++ b/packages/core/src/auth/openapi-provider.ts @@ -53,6 +53,22 @@ export function assertOAuthConfiguration( ); } +function assertOAuthRouteBinding( + profile: AliyunOAuthProfile | undefined, + credential?: Pick, +): void { + if ( + credential?.method === "aliyun-oauth" && + (!profile || + profile.session_ref !== credential.sessionRef || + credential.configurationFingerprint !== oauthConfigurationFingerprint(profile)) + ) + throw new CredentialError( + "missing-aliyun-session", + "The OAuth login changed or was removed. / OAuth 登录已变更或被移除。", + ); +} + export function oauthSessionLockPath(directory: string, reference: string): string { return join(directory, "oauth", `${reference}.lock`); } @@ -285,6 +301,7 @@ export function createOpenApiCredentialProvider( }, resolveConsoleTarget(target, purpose = "console") { const profile = selectedOAuth(currentSources(), purpose); + assertOAuthRouteBinding(profile, target); if (profile) validateTarget(profile, target); const gateway = pre ? requirePreConsoleGateway(pre, target) @@ -298,16 +315,7 @@ export function createOpenApiCredentialProvider( }, resolveHost(host, credential, purpose = "openapi") { const profile = selectedOAuth(currentSources(), purpose); - if ( - credential?.method === "aliyun-oauth" && - (!profile || - profile.session_ref !== credential.sessionRef || - credential.configurationFingerprint !== oauthConfigurationFingerprint(profile)) - ) - throw new CredentialError( - "missing-aliyun-session", - "The OAuth login changed or was removed. / OAuth 登录已变更或被移除。", - ); + assertOAuthRouteBinding(profile, credential); if (pre) return resolvePreOpenApiHost(host); if (!profile || (credential && credential.method !== "aliyun-oauth")) return host; if ( diff --git a/packages/core/src/client/console-session.ts b/packages/core/src/client/console-session.ts index 3bf5c87d6..a74670f00 100644 --- a/packages/core/src/client/console-session.ts +++ b/packages/core/src/client/console-session.ts @@ -37,6 +37,24 @@ interface ConsoleTokenRefresh { commit?: Promise; } +function assertSameConsoleIdentity( + previous?: ConsoleCredential, + next?: Pick, +): void { + if (!previous || (previous.method !== "aliyun-oauth" && next?.method !== "aliyun-oauth")) return; + if ( + previous.method !== next?.method || + !previous.sessionRef || + previous.sessionRef !== next?.sessionRef || + !previous.configurationFingerprint || + previous.configurationFingerprint !== next?.configurationFingerprint + ) + throw new CredentialError( + "changed-openapi-identity", + "The Console identity changed during the request. / 请求期间控制台身份已变更。", + ); +} + /** Internal Console credential lifecycle; each instance owns its cache and in-flight exchange. */ export class ConsoleSession { private consoleTokenPersisted: boolean; @@ -127,8 +145,14 @@ export class ConsoleSession { failure: BailianError, previous?: ConsoleCredential, ): Promise { + const retry = (credential: ConsoleCredential) => { + assertSameConsoleIdentity(previous, credential); + if (credential.method === "aliyun-oauth") + this.deps.openApiProvider?.resolveConsoleTarget(credential); + return invoke(credential); + }; if (this.deps.consoleCred && this.deps.consoleCred !== previous) - return invoke(this.deps.consoleCred); + return retry(this.deps.consoleCred); let refresh = this.consoleRefresh; if (!refresh || refresh.previous !== previous) { @@ -143,7 +167,7 @@ export class ConsoleSession { throw error; }); if (!exchange) throw failure; - const result = await invoke(exchange.credential); + const result = await retry(exchange.credential); refresh.commit ??= (async () => { if (this.deps.consoleCred !== previous) return; if (exchange.persist) { @@ -171,7 +195,10 @@ export class ConsoleSession { private async exchangeConsoleToken( previous?: ConsoleCredential, ): Promise { + if (previous?.method === "aliyun-oauth") + this.deps.openApiProvider?.resolveConsoleTarget(previous); const credential = await this.deps.resolveConsoleOpenApiCredential?.(); + assertSameConsoleIdentity(previous, credential); const unresolvedTarget = previous ? { region: previous.region, diff --git a/packages/core/src/utils/file-lock.ts b/packages/core/src/utils/file-lock.ts index 2513bcc60..a1aa0225d 100644 --- a/packages/core/src/utils/file-lock.ts +++ b/packages/core/src/utils/file-lock.ts @@ -4,7 +4,6 @@ import { mkdir, mkdtemp, readdir, - readFile, rename, rm, rmdir, @@ -19,9 +18,8 @@ import { ExitCode } from "../errors/codes.ts"; const OWNER_NAME = /^owner-([1-9]\d*)-[a-f0-9-]{36}$/u; const CONTENTION_CODES = new Set(["EEXIST", "ENOTEMPTY", "ENOTDIR", "EISDIR"]); -function ownerAlive(pid: unknown): boolean { - if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || pid > 0x7fff_ffff) - return false; +function ownerAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fff_ffff) return false; try { process.kill(pid, 0); return true; @@ -41,17 +39,12 @@ async function recoverLock(path: string): Promise { if (error.code !== "ENOENT") throw error; }); if (status?.isFile()) { - const previous = await readFile(path, "utf8").catch(() => undefined); - if (previous === undefined) return; - let pid: unknown; - try { - pid = (JSON.parse(previous) as { pid?: unknown } | null)?.pid; - } catch { - // Leave a grace period for an older process still publishing its ownership record. - if (Date.now() - status.mtimeMs < 1_000) return; - } - if (!ownerAlive(pid)) await unlink(path).catch(() => {}); - return; + // An older writer can replace this file between any ownership check and unlink. + throw new BailianError( + `Legacy lock file at ${path}. / 检测到旧版锁文件:${path}。`, + ExitCode.GENERAL, + "Stop older CLI processes and retry. If the file remains after confirming that nothing is using it, move it aside. / 请退出旧版 CLI 进程后重试;若确认锁文件已无人使用但仍存在,请将其移走。", + ); } if (!status?.isDirectory()) return; const entries = await readdir(path).catch((error: NodeJS.ErrnoException) => { diff --git a/packages/core/tests/openapi-provider.test.ts b/packages/core/tests/openapi-provider.test.ts index e1b86af99..f157368ea 100644 --- a/packages/core/tests/openapi-provider.test.ts +++ b/packages/core/tests/openapi-provider.test.ts @@ -1,5 +1,5 @@ import { spawn, type ChildProcess } from "node:child_process"; -import files, { mkdir, readFile, readdir, utimes, writeFile } from "node:fs/promises"; +import files, { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { syncBuiltinESMExports } from "node:module"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -1033,17 +1033,130 @@ describe("Console cache and endpoint isolation", () => { ); }); -describe("credential and configuration lock recovery", () => { - test.each(["", '{"pid":'])("recovers a stale incomplete lock record %j", async (record) => { - const path = join(isolation.configDir, "config.json.lock"); - await writeFile(path, record); - await writeFile(`${path}.recovery`, ""); - const stale = new Date(Date.now() - 5_000); - await utimes(path, stale, stale); - await expect(withFileLock(path, async () => true, 500)).resolves.toBe(true); - await expect(readFile(path)).rejects.toMatchObject({ code: "ENOENT" }); +describe("Console retry identity pinning", () => { + const expired = () => + json({ data: { success: false, errorCode: "BailianGateway.Login.NotLogined" } }); + const success = { data: { success: true } }; + + async function setupConsoleRetry() { + const current = profile(); + const key = consoleCredentialKey({ ...TARGET, gateway: current.console_gateway }); + const instance = await setup({ + oauthSession: session({ + sts: sts(), + consoleTokens: { [key]: { token: "fixture-console-token" } }, + }), + }); + const client = new Client({ + identity: deps.identity, + settings: buildSettings(instance.sources), + baseUrl: "https://dashscope.aliyuncs.com", + openApiProvider: instance.provider, + resolveConsoleOpenApiCredential: () => instance.provider.getCredential("console"), + }); + return { ...instance, client, key }; + } + + test.each(["new OAuth session", "static credentials"] as const)( + "does not exchange or replay under %s after the original token expires", + async (replacement) => { + const instance = await setupConsoleRetry(); + transport.mockImplementationOnce(async () => { + if (replacement === "new OAuth session") + await instance.auth.loginAliyun(profile(), session({ sts: sts() })); + else + await instance.auth.login({ + access_token: "fixture-static-console", + access_key_id: "fixture-static-id", + access_key_secret: "fixture-static-secret", + }); + return expired(); + }); + await expect(instance.client.console("fixture.readOnly", {})).rejects.toBeInstanceOf( + CredentialError, + ); + expect(transport).toHaveBeenCalledTimes(1); + expect(instance.store.read.mock.calls).toEqual([[REFERENCE]]); + }, + ); + + test("checks the fingerprint again before replay when OAuth endpoints change during issuance", async () => { + const instance = await setupConsoleRetry(); + transport.mockResolvedValueOnce(expired()).mockImplementationOnce(async () => { + await writeConfigFile({ + aliyun_oauth: profile({ modelstudio_host: "changed-modelstudio.example.test" }), + }); + return json({ cliAccessToken: "fixture-unused-token" }); + }); + await expect(instance.client.console("fixture.readOnly", {})).rejects.toBeInstanceOf( + CredentialError, + ); + expect(transport).toHaveBeenCalledTimes(2); + expect(instance.store.write).not.toHaveBeenCalled(); }); + test("a late expiry cannot replay through a replacement token loaded by another request", async () => { + const instance = await setupConsoleRetry(); + const firstStarted = deferred(); + const firstResponse = deferred(); + transport + .mockImplementationOnce(() => { + firstStarted.resolve(); + return firstResponse.promise; + }) + .mockResolvedValueOnce(json(success)); + const pending = expect(instance.client.console("fixture.firstRead", {})).rejects.toMatchObject({ + reason: "changed-openapi-identity", + }); + await firstStarted.promise; + try { + await instance.auth.loginAliyun( + profile(), + session({ + sts: sts(), + consoleTokens: { [instance.key]: { token: "fixture-replacement-console" } }, + }), + ); + await expect(instance.client.console("fixture.nextRead", {})).resolves.toEqual(success); + } finally { + firstResponse.resolve(expired()); + await pending; + } + expect(transport).toHaveBeenCalledTimes(2); + }); + + test("exchanges once and replays normally within the same OAuth session", async () => { + const instance = await setupConsoleRetry(); + transport + .mockResolvedValueOnce(expired()) + .mockResolvedValueOnce(json({ cliAccessToken: "fixture-refreshed-console" })) + .mockResolvedValueOnce(json(success)); + await expect(instance.client.console("fixture.readOnly", {})).resolves.toEqual(success); + expect(transport).toHaveBeenCalledTimes(3); + expect(transport.mock.calls[2]?.[0]).toBe(transport.mock.calls[0]?.[0]); + expect(instance.saved().consoleTokens?.[instance.key]?.token).toBe("fixture-refreshed-console"); + }); +}); + +describe("credential and configuration lock recovery", () => { + test.each(["", '{"pid":', JSON.stringify({ pid: process.pid, id: REFERENCE })])( + "does not remove or bypass a legacy lock file %j", + async (record) => { + const path = join(isolation.configDir, "config.json.lock"); + await writeFile(path, record); + await writeFile(`${path}.recovery`, ""); + const operation = vi.fn(async () => true); + const entries = (await readdir(isolation.configDir)).sort(); + await expect(withFileLock(path, operation, 500)).rejects.toMatchObject({ + message: expect.stringContaining(path), + hint: expect.stringContaining("Stop older CLI processes"), + }); + expect(operation).not.toHaveBeenCalled(); + expect(await readFile(path, "utf8")).toBe(record); + expect((await readdir(isolation.configDir)).sort()).toEqual(entries); + }, + ); + test.each(["empty", "dead owner"] as const)( "recovers a lock directory left with %s", async (state) => { From 7cb4e95008328f58a85365eb2db47562e591a6ee Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Fri, 27 Nov 2026 21:18:41 +0800 Subject: [PATCH 04/13] feat(auth): add cross-device Aliyun OAuth login Accept pasted callbacks without a local listener and protect interactive input. Keep OAuth diagnostics parseable in JSON mode and preserve help and required-flag behavior for commands with subcommands. --- README.md | 10 +- README.zh.md | 10 +- docs/agents/auth-change.md | 3 +- docs/agents/output-contract.md | 1 + packages/cli/README.md | 10 +- packages/cli/README.zh.md | 10 +- packages/commands/src/commands/auth/aliyun.ts | 236 +++++++++++++-- packages/commands/tests/auth-aliyun.test.ts | 286 ++++++++++++++++-- .../tests/output/usage-output.test.ts | 1 + packages/runtime/src/args.ts | 17 +- packages/runtime/src/registry.ts | 12 +- packages/runtime/src/resolve.ts | 30 +- .../runtime/tests/output-boundaries.test.ts | 1 + packages/runtime/tests/resolve.test.ts | 22 ++ skills/bailian-cli/reference/auth.md | 20 +- 15 files changed, 589 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index b63b69ebf..6db5ae764 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,15 @@ bl auth --login aliyun --config aliyun \ Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. -Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--no-browser` prints the URL and still waits for a callback on the same machine. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. +Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. + +For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth --login aliyun --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. + +```bash +bl auth --login aliyun --config aliyun --no-browser +``` + +The example reuses an already configured OAuth Profile; first online login still requires `--client-id` and `--authorization-url`. #### Domestic pre-release control plane diff --git a/README.zh.md b/README.zh.md index 3c68a4b2a..4f34b9a2c 100644 --- a/README.zh.md +++ b/README.zh.md @@ -201,7 +201,15 @@ bl auth --login aliyun --config aliyun \ IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 -线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--no-browser` 只禁止自动打开浏览器,仍等待同一台机器的本机回调;`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 +线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 + +SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth --login aliyun --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 + +```bash +bl auth --login aliyun --config aliyun --no-browser +``` + +示例复用已配置的 OAuth Profile;线上首次登录仍须提供 `--client-id` 和 `--authorization-url`。 #### 国内预发控制面 diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index 6e534f514..a3f7c1a97 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -79,7 +79,8 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx ### 阿里云 OAuth 登录与续期 - `bl auth --login aliyun` 是可执行的 `auth` 父命令,保留既有 `auth login/status/logout` 子命令;不在 runtime 改写 argv。 -- OAuth 回调仅监听 `127.0.0.1` 随机端口的 `/oauth/callback` 路径,授权请求与换票使用同一 `redirect_uri`。IAM 登记 `http://127.0.0.1:12345/oauth/callback`;NativeApp 忽略回环端口,但协议、主机和路径必须一致,不保留根路径兼容。 +- 默认 OAuth 回调仅监听 `127.0.0.1` 随机端口的 `/oauth/callback` 路径,授权请求与换票使用同一 `redirect_uri`。IAM 登记 `http://127.0.0.1:12345/oauth/callback`;NativeApp 忽略回环端口,但协议、主机和路径必须一致,不保留根路径兼容。 +- OAuth 的 `--no-browser` 显式选择跨设备手动授权:固定使用已登记的 `http://127.0.0.1:12345/oauth/callback`,不启服务器,在原进程粘贴完整回调 URL;校验地址、唯一且匹配的 state、唯一非空 code,拒绝 userinfo、fragment、非法查询编码、解码后包含控制字符的查询与其它登录会话。有可关闭回显的 TTY 时隐藏输入,非 TTY 提示上游终端可能回显;不保存输入历史。错误输入可重试但不重新生成 state/PKCE;有效 state 的授权拒绝、EOF、超长输入、Ctrl+C、Ctrl+Z 或超时结束登录。与默认流共用换票、落盘及取消处理,不自动降级、不提供设备码流程,不改变 `auth login --console --no-browser` 的本机回调语义。 - 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile;端点维持显式参数 > Profile > 默认地址。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和已确认的国内端点,不读线上控制面凭据、不隐式回退、不改 hosts/代理。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 - `aliyun_oauth` 仅保存端点、client_id/scope、会话引用、域激活状态及到期元数据;OAuth AT 不覆盖旧的 Console `access_token`。凭据存于配置目录下独立的 `oauth/.json` 明文文件,绑定会话引用,不写入主配置。Unix 校验目录 `0700` 和文件 `0600` 及所有者,Windows 校验私有 ACL;拒绝非普通文件及链接,使用同目录唯一临时文件、fsync 和原子替换。旧加密会话不迁移,需要重新登录。 - 同一个异步 OpenAPI provider 负责 OAuth AT/RT→STS,Console 换票与 OpenAPI 签名前复用。优先级保持 flag > 百炼 env > 所选 file(静态或 OAuth)> 阿里云 env;临时来源不落盘。`describe/stored` 只读元数据,不读取凭据文件;静态 dry-run 不调用 OAuth,框架更新/遥测仍遵循原设置。 diff --git a/docs/agents/output-contract.md b/docs/agents/output-contract.md index 9c6e40dc9..270a700bc 100644 --- a/docs/agents/output-contract.md +++ b/docs/agents/output-contract.md @@ -52,6 +52,7 @@ stdout 与 stderr 分别解析:stdout 是一个 JSON 文档;stderr 的每个 | speech synthesize | text 且没有 `--out` 时允许原始音频 stdout | 流式 JSON 要求 `--out`,副作用前校验;dry-run 保留预览 | | pipeline run `--events jsonl` | 显式 `--output text` 保留既有生命周期 JSONL 流 | 与有效 JSON 格式冲突时,在读取/执行工作流前报用法错误 | | 浏览器登录 / 终端问答 / 本地 UI / Workbench | text 原生交互;登录 URL、问题和 Workbench 子进程使用其原生通道;Workbench ready/reuse URL 是最终结果 | 无法满足普通结果契约的原生模式在浏览器、服务器、子进程或远程副作用前拒绝,提示 text 或既有非交互方式;dry-run 保留结构预览 | +| 阿里云 OAuth 登录(浏览器回调及手动粘贴) | 登录链接及交互提示写原生 stderr,不受 quiet 影响 | 登录链接和提示通过 reporter 以 JSONL warning 写 stderr;授权码、PKCE verifier 和令牌不输出;dry-run 不启动登录 | | help / version / introspect | runtime 负责的产品入口及协议输出 | 沿用各入口专属协议,不当成普通业务结果 | | Command Pack API 1 | 兼容已有 result/line/write 表面;按调用缓存并最终提交一次 result | 显式 result 保留数据;只有 raw write 时返回累计字符串;重复 result 报协议错误。用户扩展自行调用 process/console 不属于宿主 API 保证 | diff --git a/packages/cli/README.md b/packages/cli/README.md index b63b69ebf..6db5ae764 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -202,7 +202,15 @@ bl auth --login aliyun --config aliyun \ Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. -Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--no-browser` prints the URL and still waits for a callback on the same machine. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. +Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. + +For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth --login aliyun --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. + +```bash +bl auth --login aliyun --config aliyun --no-browser +``` + +The example reuses an already configured OAuth Profile; first online login still requires `--client-id` and `--authorization-url`. #### Domestic pre-release control plane diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index 3c68a4b2a..4f34b9a2c 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -201,7 +201,15 @@ bl auth --login aliyun --config aliyun \ IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 -线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--no-browser` 只禁止自动打开浏览器,仍等待同一台机器的本机回调;`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 +线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 + +SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth --login aliyun --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 + +```bash +bl auth --login aliyun --config aliyun --no-browser +``` + +示例复用已配置的 OAuth Profile;线上首次登录仍须提供 `--client-id` 和 `--authorization-url`。 #### 国内预发控制面 diff --git a/packages/commands/src/commands/auth/aliyun.ts b/packages/commands/src/commands/auth/aliyun.ts index 14e720756..e4d8cdeb1 100644 --- a/packages/commands/src/commands/auth/aliyun.ts +++ b/packages/commands/src/commands/auth/aliyun.ts @@ -1,4 +1,6 @@ import http from "node:http"; +import { createInterface } from "node:readline"; +import { PassThrough, type Readable } from "node:stream"; import { ALIYUN_CLI_CLIENT_ID, ALIYUN_CLI_SCOPE, @@ -40,11 +42,12 @@ export interface AliyunOAuthLoginDeps { identity: Identity; settings: Settings; authStore: Pick; - output: Pick; + output: Pick; localize?: (text: LocalizedText) => string; writeStderr?: (text: string) => void; openBrowser?: (url: string) => void | Promise; onAuthUrl?: (url: string) => void | Promise; + stdin?: Readable & { isTTY?: boolean; setRawMode?: (mode: boolean) => unknown }; } export interface AliyunOAuthLoginOptions { @@ -205,6 +208,189 @@ function assertActive(signal: AbortSignal, deps: AliyunOAuthLoginDeps): void { if (signal.aborted) throw interrupted(deps); } +function loginPromptWriter(deps: AliyunOAuthLoginDeps): (text: string) => void { + if (deps.settings.output === "json") { + return (text) => { + const message = text.trim(); + if (message) deps.output.warning(message); + }; + } + return deps.writeStderr ?? ((text) => process.stderr.write(text)); +} + +async function receiveManualCode( + deps: AliyunOAuthLoginDeps, + profile: LoginProfile, + proof: ReturnType, + options: AliyunOAuthLoginOptions, + signal: AbortSignal, +): Promise<{ code: string; redirectUri: string }> { + const input = deps.stdin ?? process.stdin; + const closedInput = () => + new BailianError( + localize(deps, { + "en-US": "Callback input closed before authorization was received.", + "zh-CN": "尚未收到授权回调,输入已关闭。", + }), + ExitCode.GENERAL, + ); + if (input.destroyed || input.readableEnded) throw closedInput(); + const redirectUri = `http://127.0.0.1:12345${OAUTH_CALLBACK_PATH}`; + const authUrl = aliyunAuthorizationUrl(profile, redirectUri, proof); + const writeStderr = loginPromptWriter(deps); + const hiddenInput = !!input.isTTY && typeof input.setRawMode === "function"; + const prompt = () => + writeStderr( + localize( + deps, + hiddenInput + ? { + "en-US": "Callback URL (input hidden; Ctrl+C to cancel): ", + "zh-CN": "回调 URL(输入不回显;按 Ctrl+C 取消):", + } + : { + "en-US": "Callback URL (Ctrl+C to cancel): ", + "zh-CN": "回调 URL(按 Ctrl+C 取消):", + }, + ), + ); + // Bound input before readline can buffer it, and keep its TTY decoder off shared stdin. + const callbackInput = Object.assign(new PassThrough(), { + setRawMode: (mode: boolean) => input.setRawMode?.(mode), + }); + const reader = createInterface({ + input: callbackInput, + terminal: hiddenInput, + historySize: 0, + crlfDelay: Infinity, + }); + let finished = false; + let resolveCode!: (code: string) => void; + let rejectCode!: (error: unknown) => void; + const completion = new Promise((resolve, reject) => { + resolveCode = resolve; + rejectCode = reject; + }); + void completion.catch(() => {}); + const settle = (code?: string, error?: BailianError) => { + if (finished) return; + finished = true; + if (error) rejectCode(error); + else resolveCode(code!); + }; + const onLine = (answer: string) => { + if (finished) return; + const raw = answer.trim(); + if (raw.startsWith(`${redirectUri}?`) && !/[\p{Cc}\s#]/u.test(raw)) { + try { + const decodedQuery = decodeURIComponent(raw.slice(redirectUri.length + 1)); + if (!/\p{Cc}/u.test(decodedQuery)) { + settle(parseAliyunCallback(new URL(raw), proof.state)); + return; + } + } catch (error) { + if (error instanceof BailianError && !(error instanceof UsageError)) { + settle(undefined, error); + return; + } + } + } + writeStderr( + `\n${localize(deps, { + "en-US": "Invalid OAuth callback address. Paste the complete callback URL for this login.", + "zh-CN": "OAuth 回调地址无效,请粘贴本次登录的完整回调 URL。", + })}\n`, + ); + prompt(); + }; + let pendingBytes = 0; + const onData = (chunk: Buffer | string) => { + const bytes = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk; + let start = 0; + for (const [offset, byte] of bytes.entries()) { + if (finished) return; + if (byte === 10 || byte === 13) { + pendingBytes = 0; + callbackInput.write(bytes.subarray(start, offset + 1)); + start = offset + 1; + } else if (++pendingBytes >= 16 * 1024) { + settle( + undefined, + new UsageError("OAuth callback URL is too long. / OAuth 回调 URL 过长。"), + ); + return; + } + } + if (!finished && start < bytes.length) callbackInput.write(bytes.subarray(start)); + }; + const onAbort = () => settle(undefined, interrupted(deps)); + const onClose = () => settle(undefined, closedInput()); + const onEnd = () => callbackInput.end(); + reader.on("line", onLine); + reader.on("SIGINT", onAbort); + // Readline would restore echo before trying to suspend, even if the shell cannot suspend us. + reader.on("SIGTSTP", onAbort); + reader.on("close", onClose); + input.on("error", onClose); + input.on("end", onEnd); + input.on("close", onEnd); + input.on("data", onData); + signal.addEventListener("abort", onAbort, { once: true }); + const timer = setTimeout( + () => + settle( + undefined, + new BailianError( + localize(deps, { + "en-US": "Aliyun OAuth login timed out waiting for the pasted callback URL.", + "zh-CN": "阿里云 OAuth 登录等待粘贴回调 URL 超时。", + }), + ExitCode.TIMEOUT, + ), + ), + options.callbackTimeoutMs ?? CALLBACK_TIMEOUT_MS, + ); + try { + assertActive(signal, deps); + if (!hiddenInput) + writeStderr( + `${localize(deps, { + "en-US": + "Warning: your terminal may echo the callback URL. To hide input in an interactive SSH or container session, allocate a TTY (ssh -t or docker exec -it).", + "zh-CN": + "警告:终端可能回显回调 URL。如需隐藏交互输入,请为 SSH 或容器会话分配 TTY(ssh -t 或 docker exec -it)。", + })}\n\n`, + ); + writeStderr( + `${localize(deps, { + "en-US": "Open this login URL in a browser on your computer or phone:", + "zh-CN": "请在电脑或手机浏览器中打开以下登录地址:", + })}\n${authUrl}\n\n${localize(deps, { + "en-US": `After authorizing, the browser redirects to ${redirectUri}. The page may fail to load; this is expected. Copy the entire URL from the address bar, including code and state, and paste it only into this terminal.`, + "zh-CN": `授权后浏览器会跳转到 ${redirectUri}。页面打不开是正常现象;请复制地址栏中的完整 URL(含 code 和 state),只粘贴到此终端。`, + })}\n`, + ); + prompt(); + if (deps.onAuthUrl) + void Promise.resolve() + .then(() => deps.onAuthUrl!(authUrl)) + .catch(onClose); + return { code: await completion, redirectUri }; + } finally { + finished = true; + clearTimeout(timer); + signal.removeEventListener("abort", onAbort); + input.off("data", onData); + input.off("end", onEnd); + input.off("close", onEnd); + input.off("error", onClose); + input.pause(); + reader.close(); + callbackInput.destroy(); + writeStderr("\n"); + } +} + /** Only this process's callback server and listeners are owned by this function. */ async function receiveCode( deps: AliyunOAuthLoginDeps, @@ -214,6 +400,7 @@ async function receiveCode( signal: AbortSignal, ): Promise<{ code: string; redirectUri: string }> { assertActive(signal, deps); + if (options.noBrowser) return receiveManualCode(deps, profile, proof, options, signal); let finished = false; let timer: ReturnType | undefined; let resolveCode!: (code: string) => void; @@ -296,11 +483,7 @@ async function receiveCode( const onAbort = () => settle(undefined, interrupted(deps)); server.on("error", onError); signal.addEventListener("abort", onAbort, { once: true }); - const writeStderr = - deps.writeStderr ?? - ((text: string) => { - process.stderr.write(text); - }); + const writeStderr = loginPromptWriter(deps); try { const port = await listenLocalServer(server, 0); assertActive(signal, deps); @@ -333,20 +516,18 @@ async function receiveCode( void Promise.resolve() .then(() => deps.onAuthUrl!(authUrl)) .catch(onError); - if (!options.noBrowser) { - // Never await browser launch: it can fail, hang, or deliver an immediate callback. - void Promise.resolve() - .then(() => (deps.openBrowser ?? openInBrowser)(authUrl)) - .catch(() => { - if (!finished) - writeStderr( - `${localize(deps, { - "en-US": "Could not open the browser. Open the URL above manually.", - "zh-CN": "无法自动打开浏览器,请手动打开上方地址。", - })}\n`, - ); - }); - } + // Never await browser launch: it can fail, hang, or deliver an immediate callback. + void Promise.resolve() + .then(() => (deps.openBrowser ?? openInBrowser)(authUrl)) + .catch(() => { + if (!finished) + writeStderr( + `${localize(deps, { + "en-US": "Could not open the browser. Open the URL above manually.", + "zh-CN": "无法自动打开浏览器,请手动打开上方地址。", + })}\n`, + ); + }); return { code: await completion, redirectUri }; } finally { finished = true; @@ -451,8 +632,8 @@ export async function runAliyunOAuthLogin( }, { text: localize(deps, { - "en-US": `Would authorize Aliyun OAuth with a random loopback port, exchange STS, validate Console access and save the session. ${missingClientId ? "Missing required options" : "Missing endpoints"}: ${missing.join(", ") || "none"}.${preEndpoints}`, - "zh-CN": `将通过随机回环端口完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。${missingClientId ? "缺少必填选项" : "缺少端点"}:${missing.join("、") || "无"}。${preEndpoints}`, + "en-US": `Would authorize Aliyun OAuth ${options.noBrowser ? "by pasting the callback URL without listening on a port" : "with a random loopback port"}, exchange STS, validate Console access and save the session. ${missingClientId ? "Missing required options" : "Missing endpoints"}: ${missing.join(", ") || "none"}.${preEndpoints}`, + "zh-CN": `将${options.noBrowser ? "通过粘贴回调 URL(不监听端口)" : "通过随机回环端口"}完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。${missingClientId ? "缺少必填选项" : "缺少端点"}:${missing.join("、") || "无"}。${preEndpoints}`, }), }, ); @@ -573,9 +754,10 @@ export default defineCommand({ description: { "en-US": "Authenticate with Aliyun OAuth", "zh-CN": "通过阿里云 OAuth 登录" }, auth: "none", usageArgs: - "--login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ]", + "--login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ] [--no-browser]", exampleArgs: [ "--login aliyun --client-id --authorization-url ", + "--login aliyun --client-id --authorization-url --no-browser", "--login aliyun --client-id --authorization-url --modelstudio-host --console-gateway ", ], flags: { @@ -654,17 +836,17 @@ export default defineCommand({ noBrowser: { type: "switch", description: { - "en-US": "Do not open the browser automatically; still wait for the local callback", - "zh-CN": "不自动打开浏览器;仍等待本机回调", + "en-US": "Authorize on another device and paste the full callback URL; no local listener", + "zh-CN": "在其它设备授权后粘贴完整回调 URL;不监听本地端口", }, }, }, notes: [ { "en-US": - "Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. No device flow or remote callback import is supported.", + "Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. With --no-browser, paste the complete callback URL into this login session; this is not device authorization.", "zh-CN": - "非预发环境首次登录需要显式指定客户端 ID 和已确认的授权地址。预发端点覆盖必须与可信端点一致,并且必须配置 CLI 网关。不支持设备授权或导入远程回调。", + "非预发环境首次登录需要显式指定客户端 ID 和已确认的授权地址。预发端点覆盖必须与可信端点一致,并且必须配置 CLI 网关。使用 --no-browser 时须在本次登录会话中粘贴完整回调 URL;这不是设备授权。", }, { "en-US": diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index fca863103..ae9549fc1 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -1,4 +1,7 @@ import http from "node:http"; +import { PassThrough } from "node:stream"; +import { execFile } from "node:child_process"; +import { fileURLToPath } from "node:url"; import { createHash } from "node:crypto"; import { ALIYUN_CLI_CLIENT_ID, @@ -19,7 +22,7 @@ import { type PreControlPlane, } from "bailian-cli-core"; import { createOutputReporter } from "bailian-cli-runtime"; -import { enterIsolatedHome, type IsolatedHomeHandle } from "e2e/isolation"; +import { buildIsolatedCliEnv, enterIsolatedHome, type IsolatedHomeHandle } from "e2e/isolation"; import { afterEach, beforeEach, expect, test, vi, type MockInstance } from "vite-plus/test"; import authRoot, { runAliyunOAuthLogin, @@ -207,6 +210,7 @@ function launch( verbose?: boolean; omitEndpoints?: boolean; preControlPlane?: PreControlPlane; + stdin?: AliyunOAuthLoginDeps["stdin"]; } = {}, ) { const stdout: string[] = []; @@ -262,6 +266,7 @@ function launch( authStore: { describe, loginAliyun: save }, onAuthUrl: url.resolve, openBrowser: browser, + stdin: settingsOptions.stdin, }; const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) @@ -511,8 +516,11 @@ test("完整 OAuth→STS→显式 POP→显式网关→保存链路使用 PKCE console: true, openapi: true, }); - expect(probe.stderr.join("")).toContain(authUrl); - expect(probe.stderr.join("")).toContain("Waiting for the local OAuth callback"); + expect(probe.stderr).toHaveLength(1); + expect(JSON.parse(probe.stderr[0]!)).toEqual({ + warning: { message: expect.stringContaining(authUrl) }, + }); + expect(probe.stderr[0]).toContain("Waiting for the local OAuth callback"); assertNoSecrets(probe, [verifier]); assertSignalCleanup(probe); expect(createServer.mock.results[0]!.value.address()).toBeNull(); @@ -520,23 +528,244 @@ test("完整 OAuth→STS→显式 POP→显式网关→保存链路使用 PKCE }); test.each(["text", "json"] as const)( - "双语成功结果仅含安全状态,登录链接仍写 stderr (%s)", + "双语成功结果仅含安全状态,登录链接写入对应格式的 stderr (%s)", async (output) => { - const probe = launch({}, { output, language: "zh-CN" }); - await finish(probe); - expect(probe.stderr.join("")).toContain("请在本机浏览器中打开"); - expect(probe.stderr.join("")).toContain("正在等待本机 OAuth 回调"); - if (output === "text") + const probe = launch({}, { output, language: "zh-CN", quiet: true }); + const { authUrl } = await finish(probe); + const prompt = `请在本机浏览器中打开以下登录地址:\n${authUrl}\n正在等待本机 OAuth 回调。按 Ctrl+C 取消。`; + expect(probe.stderr).toHaveLength(1); + if (output === "text") { + expect(probe.stderr[0]).toBe(`${prompt}\n`); expect(probe.stdout.join("")).toBe( "阿里云 OAuth 登录成功(配置:oauth-test;console:true;openapi:true)。\n", ); - else expect(JSON.parse(probe.stdout.join("")).authenticated).toBe(true); + } else { + expect(JSON.parse(probe.stderr[0]!)).toEqual({ warning: { message: prompt } }); + expect(JSON.parse(probe.stdout.join("")).authenticated).toBe(true); + } + assertNoSecrets(probe); + }, +); + +test.each(["en-US", "zh-CN"] as const)( + "无浏览器模式在其它设备授权后粘回 URL,复用 PKCE 和四段换票且不监听端口 (%s)", + async (language) => { + const input = new PassThrough(); + const listen = vi.spyOn(http.Server.prototype, "listen"); + const createServer = vi.spyOn(http, "createServer"); + const probe = launch({ noBrowser: true }, { stdin: input, language }); + const authUrl = await probe.authUrl; + const callback = callbackUrl(authUrl); + expect(callback.origin + callback.pathname).toBe("http://127.0.0.1:12345/oauth/callback"); + expect(listen).not.toHaveBeenCalled(); + expect(createServer).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + input.end(callback.href); + expect(await probe.outcome).toBeUndefined(); + const form = new URLSearchParams(stringBody(requests[0]!.init.body)); + expect(form.get("redirect_uri")).toBe(callback.origin + callback.pathname); + expect(form.get("code")).toBe(SECRETS.code); + expect(new URL(authUrl).searchParams.get("code_challenge")).toBe( + createHash("sha256").update(form.get("code_verifier")!, "ascii").digest("base64url"), + ); + expect(requests.map((request) => request.url.pathname)).toEqual(Object.values(STAGE_PATHS)); + expect(probe.save).toHaveBeenCalledTimes(1); + expect(probe.stderr.map((line) => JSON.parse(line))).toEqual([ + { warning: { message: expect.stringContaining("ssh -t") } }, + { warning: { message: expect.stringContaining(authUrl) } }, + { warning: { message: expect.stringMatching(/Callback URL|回调 URL/u) } }, + ]); + expect(probe.stderr.join("")).toContain( + language === "zh-CN" ? "电脑或手机浏览器" : "browser on your computer or phone", + ); + expect(probe.stderr.join("")).toContain(language === "zh-CN" ? "可能回显" : "may echo"); + expect(probe.stderr.join("")).toContain("ssh -t"); + expect(probe.stderr.join("")).not.toMatch( + /输入不回显|input hidden|Waiting for the local OAuth callback/u, + ); + assertNoSecrets(probe, [callback.href, form.get("code_verifier")!]); + assertSignalCleanup(probe); + expect(input.listenerCount("data")).toBe(0); + expect(input.listenerCount("error")).toBe(0); + }, +); + +test("粘贴无效回调仅重试本次会话,不换票、不回显原文", async () => { + const input = new PassThrough(); + const probe = launch({ noBrowser: true }, { stdin: input }); + const authUrl = await probe.authUrl; + const callback = callbackUrl(authUrl); + const invalid = [ + "", + SECRETS.code, + "not-a-url", + callback.href + "#", + ...["%ZZ", "%FF", "%C3", "%00", "%0A", "%C2%85"].map((suffix) => callback.href + suffix), + ]; + for (const replacement of [ + "https://127.0.0.1:12345/oauth/callback", + "http://localhost:12345/oauth/callback", + "http://127.0.0.1:12346/oauth/callback", + "http://127.0.0.1:12345/cli/callback", + "http://127.0.0.1:12345/oauth/callback/", + "http://127.0.0.1:12345/other/../oauth/callback", + "http://user@127.0.0.1:12345/oauth/callback", + ]) + invalid.push(callback.href.replace(callback.origin + callback.pathname, replacement)); + const wrongState = new URL(callback); + wrongState.searchParams.set("state", "wrong-state"); + wrongState.searchParams.set("error", "access_denied"); + invalid.push(wrongState.href); + for (const key of ["state", "code"]) { + const absent = new URL(callback); + absent.searchParams.delete(key); + invalid.push(absent.href); + const duplicate = new URL(callback); + duplicate.searchParams.append(key, duplicate.searchParams.get(key)!); + invalid.push(duplicate.href); + } + const emptyCode = new URL(callback); + emptyCode.searchParams.set("code", " "); + invalid.push(emptyCode.href); + for (const answer of invalid) input.write(answer + "\n"); + expect(probe.stderr.join("").match(/Invalid OAuth callback address/g)).toHaveLength( + invalid.length, + ); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + input.end(callback.href + "\r\n"); + expect(await probe.outcome).toBeUndefined(); + expect(new URLSearchParams(stringBody(requests[0]!.init.body)).get("code")).toBe(SECRETS.code); + assertNoSecrets(probe, [callback.href]); +}); + +test.each(process.platform === "win32" ? ["Ctrl+C"] : ["Ctrl+C", "Ctrl+Z"])( + "TTY 输入不回显且 %s 取消并清理 raw mode", + async (key) => { + const input = Object.assign(new PassThrough(), { isTTY: true, setRawMode: vi.fn() }); + const probe = launch({ noBrowser: true }, { stdin: input }); + const callback = callbackUrl(await probe.authUrl); + expect(probe.stderr.join("")).toContain("input hidden"); + expect(probe.stderr.join("")).not.toContain("may echo"); + expect(input.setRawMode).toHaveBeenCalledWith(true); + input.write(callback.href); + expect(fetchMock).not.toHaveBeenCalled(); + input.write(key === "Ctrl+C" ? "\u0003" : "\u001a"); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.INTERRUPTED }); + expect(input.setRawMode).toHaveBeenLastCalledWith(false); + expect(probe.save).not.toHaveBeenCalled(); + assertNoSecrets(probe, [callback.href]); + assertSignalCleanup(probe); + expect(input.listenerCount("data")).toBe(0); + input.destroy(); + }, +); + +test.each(["EOF", "error", "oversize", "denied"] as const)( + "手动回调的%s终止而不换票或保存", + async (kind) => { + const input = new PassThrough(); + const probe = launch({ noBrowser: true }, { stdin: input }); + const authUrl = await probe.authUrl; + if (kind === "EOF") input.end(); + else if (kind === "error") input.emit("error", new Error(SECRETS.refreshToken)); + else if (kind === "oversize") { + input.write("x".repeat(8192)); + input.write("x".repeat(8192)); + } else + input.write( + callbackUrl(authUrl, { error: "access_denied", error_description: SECRETS.refreshToken }) + .href + "\n", + ); + const error = await probe.outcome; + expect(error).toMatchObject({ + exitCode: kind === "oversize" ? ExitCode.USAGE : ExitCode.GENERAL, + }); + probe.reporter.error(error); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); assertNoSecrets(probe); + assertSignalCleanup(probe); + expect(input.listenerCount("data")).toBe(0); + input.destroy(); + }, +); + +test.each(["abort", "SIGINT", "SIGTERM", "timeout"] as const)( + "等待手动回调期间%s清理输入和计时器", + async (kind) => { + vi.useFakeTimers(); + const input = new PassThrough(); + const probe = launch({ noBrowser: true, callbackTimeoutMs: 100 }, { stdin: input }); + await probe.authUrl; + await vi.advanceTimersByTimeAsync(99); + expect(fetchMock).not.toHaveBeenCalled(); + if (kind === "timeout") await vi.advanceTimersByTimeAsync(1); + else if (kind === "abort") probe.controller.abort(); + else Reflect.apply(process.listeners(kind).at(-1)!, process, []); + expect(await probe.outcome).toMatchObject({ + exitCode: kind === "timeout" ? ExitCode.TIMEOUT : ExitCode.INTERRUPTED, + }); + expect(vi.getTimerCount()).toBe(0); + expect(input.listenerCount("data")).toBe(0); + expect(probe.save).not.toHaveBeenCalled(); + assertSignalCleanup(probe); + input.destroy(); }, ); +// A real product invocation checks flag routing, stdin EOF and exit without a browser or network fixture. +test("产品子进程的手动登录从 stdin 读取,回调无效后遇到 EOF 退出", async () => { + const environment = buildIsolatedCliEnv({ + overrides: { + BAILIAN_PRE: "0", + NODE_OPTIONS: "", + NODE_NO_WARNINGS: "1", + DO_NOT_TRACK: "1", + NO_UPDATE_NOTIFIER: "1", + }, + }); + try { + const result = await new Promise<{ + exitCode: number | string | undefined; + stdout: string; + stderr: string; + }>((resolve, reject) => { + const child = execFile( + process.execPath, + [ + "--import", + import.meta.resolve("tsx"), + fileURLToPath(new URL("../../cli/src/main.ts", import.meta.url)), + "auth", + "--login", + "aliyun", + "--no-browser", + "--client-id", + "test-client", + "--authorization-url", + ENDPOINTS.authorizationUrl, + ], + { env: environment.env, encoding: "utf8", timeout: 7000, killSignal: "SIGKILL" }, + (error, stdout, stderr) => resolve({ exitCode: error?.code ?? undefined, stdout, stderr }), + ); + child.stdin!.once("error", reject); + child.stdin!.end(SECRETS.code + "\n"); + }); + expect(result.exitCode).toBe(ExitCode.GENERAL); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("your terminal may echo the callback URL"); + expect(result.stderr).not.toContain("input hidden"); + expect(result.stderr).toContain("Paste the complete callback URL"); + expect(result.stderr).toContain("Callback input closed before authorization was received"); + expect(result.stderr).not.toContain(SECRETS.code); + } finally { + environment.dispose(); + } +}, 10_000); + test("错误或重复 state、缺失或重复 code 均拒绝并继续等待,有效 state 的拒绝不能被错误 state 伪造", async () => { - const probe = launch({ noBrowser: true }); + const probe = launch(); const authUrl = await probe.authUrl; const callback = callbackUrl(authUrl); const malformed: URL[] = []; @@ -561,7 +790,7 @@ test("错误或重复 state、缺失或重复 code 均拒绝并继续等待, expect(probe.save).not.toHaveBeenCalled(); expect((await localRequest(callback)).status).toBe(200); expect(await probe.outcome).toBeUndefined(); - expect(probe.browser).not.toHaveBeenCalled(); + expect(probe.browser).toHaveBeenCalledTimes(1); assertNoSecrets(probe); }); @@ -628,7 +857,7 @@ test("打开浏览器时即刻回调不会漏掉完成事件", async () => { }); test("真实短超时关闭服务器且不产生请求、保存或遗留信号监听器", async () => { - const probe = launch({ callbackTimeoutMs: 20, noBrowser: true }); + const probe = launch({ callbackTimeoutMs: 20 }); const callback = callbackUrl(await probe.authUrl); expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.TIMEOUT }); expect(fetchMock).not.toHaveBeenCalled(); @@ -639,7 +868,7 @@ test("真实短超时关闭服务器且不产生请求、保存或遗留信号 test("受控时间推进覆盖超时边界并清除本次定时器", async () => { vi.useFakeTimers(); - const probe = launch({ callbackTimeoutMs: 100, noBrowser: true }); + const probe = launch({ callbackTimeoutMs: 100 }); await probe.authUrl; await vi.advanceTimersByTimeAsync(99); expect(probe.save).not.toHaveBeenCalled(); @@ -653,7 +882,7 @@ test("受控时间推进覆盖超时边界并清除本次定时器", async () => test.each(["abort", "SIGINT", "SIGTERM"] as const)( "等待回调期间%s取消并清理服务器", async (kind) => { - const probe = launch({ noBrowser: true }); + const probe = launch(); const callback = callbackUrl(await probe.authUrl); if (kind === "abort") probe.controller.abort(new Error(SECRETS.accessToken)); else { @@ -703,7 +932,7 @@ test.each(STAGES)("%s 请求在途时 Ctrl+C 中止换票,仅撤销已获得 } }, }; - const probe = launch({ noBrowser: true }); + const probe = launch(); try { expect((await localRequest(callbackUrl(await probe.authUrl))).status).toBe(200); const requestSignal = await Promise.race([ @@ -842,7 +1071,7 @@ test("下游阶段取消不保存,并撤销已经获得的 RT", async () => { }); test("已开始持久化时取消,不撤销成功保存的会话", async () => { - const probe = launch({ noBrowser: true }); + const probe = launch(); probe.save.mockImplementation(async () => probe.controller.abort()); await finish(probe); expect(probe.save).toHaveBeenCalledTimes(1); @@ -986,8 +1215,13 @@ test.each([true, false])( "dry-run 零秘密读取/监听/浏览器/请求/保存,允许缺端点 (%s)", async (omitEndpoints) => { const listen = vi.spyOn(http.Server.prototype, "listen"); - const probe = launch({}, { dryRun: true, omitEndpoints }); + const input = new PassThrough(); + const probe = launch( + { noBrowser: omitEndpoints }, + { dryRun: true, omitEndpoints, stdin: input }, + ); expect(await probe.outcome).toBeUndefined(); + expect(input.listenerCount("data")).toBe(0); expect(probe.describe).not.toHaveBeenCalled(); expect(listen).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled(); @@ -996,6 +1230,7 @@ test.each([true, false])( expect(probe.stderr).toEqual([]); const data = JSON.parse(probe.stdout.join("")); expect(data.method).toBe("aliyun"); + expect(data.no_browser).toBe(omitEndpoints); expect(data.missing).toEqual(omitEndpoints ? ["--authorization-url"] : []); expect(data.plan.modelstudio_host).toBe( omitEndpoints ? DEFAULT_ENDPOINTS.modelstudioHost : ENDPOINTS.modelstudioHost, @@ -1013,6 +1248,21 @@ test.each([true, false])( }, ); +test.each([ + [false, "en-US", "with a random loopback port"], + [true, "en-US", "by pasting the callback URL without listening on a port"], + [false, "zh-CN", "通过随机回环端口"], + [true, "zh-CN", "通过粘贴回调 URL(不监听端口)"], +] as const)("OAuth 文本预览按模式显示回调方式 (%s, %s)", async (noBrowser, language, text) => { + const probe = launch({ noBrowser }, { dryRun: true, output: "text", language }); + expect(await probe.outcome).toBeUndefined(); + expect(probe.stdout.join("")).toContain(text); + if (noBrowser) expect(probe.stdout.join("")).not.toMatch(/random loopback port|随机回环端口/u); + expect(probe.stderr).toEqual([]); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + test("预发 OAuth 首次登录预览列出预设端点和未确认的 Console 网关", async () => { const probe = launch({}, { dryRun: true, omitEndpoints: true, preControlPlane: {} }); expect(await probe.outcome).toBeUndefined(); diff --git a/packages/commands/tests/output/usage-output.test.ts b/packages/commands/tests/output/usage-output.test.ts index d9c47fda3..58b1109f0 100644 --- a/packages/commands/tests/output/usage-output.test.ts +++ b/packages/commands/tests/output/usage-output.test.ts @@ -291,6 +291,7 @@ async function invoke( }); const client = { baseUrl: REGIONS.cn, + resolveOpenApiHost: (host: string) => host, console: async (api: string, data: Record) => { calls.push({ api, data: structuredClone(data) }); if (failure) throw new BailianError("Original console failure", ExitCode.GENERAL); diff --git a/packages/runtime/src/args.ts b/packages/runtime/src/args.ts index 483779271..df691e7a9 100644 --- a/packages/runtime/src/args.ts +++ b/packages/runtime/src/args.ts @@ -250,14 +250,19 @@ export function parseFlags( } } - // Required enforcement — declarative, driven by the schema. + if (options.enforceRequired !== false) assertRequiredFlags(defs, flags, localize); + return flags as unknown as ParsedFlags; +} + +export function assertRequiredFlags( + defs: FlagsDef, + flags: Record, + localize: Translator["localize"], +): void { const missing = Object.entries(defs) .filter( ([key, definition]) => - options.enforceRequired !== false && - definition.type !== "switch" && - definition.required === true && - flags[key] === undefined, + definition.type !== "switch" && definition.required === true && flags[key] === undefined, ) .map(([key]) => `--${camelToKebab(key)}`); if (missing.length > 0) { @@ -266,6 +271,4 @@ export function parseFlags( "zh-CN": `缺少必填参数:${missing.join(", ")}`, }); } - - return flags as unknown as ParsedFlags; } diff --git a/packages/runtime/src/registry.ts b/packages/runtime/src/registry.ts index edb98baf9..ad797f475 100644 --- a/packages/runtime/src/registry.ts +++ b/packages/runtime/src/registry.ts @@ -97,7 +97,7 @@ const HELP_TEXT = { * tokens (no positionals); `error` carries the message + hint. */ export type LocateResult = - | { kind: "leaf"; command: AnyCommand; matched: string[] } + | { kind: "leaf"; command: AnyCommand; matched: string[]; hasChildren: boolean } | { kind: "group"; matched: string[] } | { kind: "unknown"; error: UsageError }; @@ -217,7 +217,12 @@ export class CommandRegistry { if (node.command) { const leftover = commandPath.slice(matched.length); if (leftover.length === 0) { - return { kind: "leaf", command: node.command, matched }; + return { + kind: "leaf", + command: node.command, + matched, + hasChildren: node.children.size > 0, + }; } return { kind: "unknown", @@ -353,6 +358,9 @@ export class CommandRegistry { // Hybrid leaf+group (e.g. `omni` + `omni translate`): append child commands. if (node.children.size > 0) { const prefix = commandPath.join(" "); + out.write( + `\n${this.bold(this.localize(HELP_TEXT.usage), out)} ${this.cliName} ${prefix} [flags]\n`, + ); out.write(`\n${this.bold(this.localize(HELP_TEXT.subcommands), out)}\n`); this.printChildren(node, prefix, out); } diff --git a/packages/runtime/src/resolve.ts b/packages/runtime/src/resolve.ts index bc92fc680..23697b816 100644 --- a/packages/runtime/src/resolve.ts +++ b/packages/runtime/src/resolve.ts @@ -7,7 +7,7 @@ import { validateTimeout, } from "bailian-cli-core"; import type { CommandRegistry } from "./registry.ts"; -import { parseFlags, parsePath } from "./args.ts"; +import { assertRequiredFlags, parseFlags, parsePath } from "./args.ts"; import { confirmationFlagDefs } from "./confirm.ts"; import { createTranslator, type Translator } from "./i18n.ts"; @@ -65,18 +65,22 @@ export function resolve( ...target.command.flags, } : GLOBAL_FLAGS; - let parsedFlags: Record; - try { - parsedFlags = parseFlags(rest, definitions, localize, { - enforceRequired: - target.kind === "leaf" && !hasHelpFlag && !hasVersionFlag && !hasIntrospectFlag, - }); - } catch (error) { - // A bare leaf with missing required flags remains an incomplete invocation. - if (error instanceof UsageError && target.kind === "leaf" && rest.length === 0) { - return { kind: "help", path: target.matched, parsedFlags: {} }; + const parsedFlags = parseFlags(rest, definitions, localize, { enforceRequired: false }); + let showHelp = hasHelpFlag; + if (target.kind === "leaf" && !hasHelpFlag && !hasVersionFlag && !hasIntrospectFlag) { + try { + assertRequiredFlags(definitions, parsedFlags, localize); + } catch (error) { + const onlyGlobalFlags = + target.hasChildren && + Object.entries(parsedFlags).every( + ([key, value]) => + Object.hasOwn(GLOBAL_FLAGS, key) || + (definitions[key]?.type === "switch" && value === false), + ); + if (!(error instanceof UsageError) || (rest.length !== 0 && !onlyGlobalFlags)) throw error; + showHelp = true; } - throw error; } if (parsedFlags.timeout !== undefined) { @@ -91,7 +95,7 @@ export function resolve( switch (target.kind) { case "leaf": - return hasHelpFlag + return showHelp ? { kind: "help", path: target.matched, parsedFlags } : { kind: "run", path: target.matched, command: target.command, rest, parsedFlags }; case "group": diff --git a/packages/runtime/tests/output-boundaries.test.ts b/packages/runtime/tests/output-boundaries.test.ts index 0f552d1a9..a4ab0aa01 100644 --- a/packages/runtime/tests/output-boundaries.test.ts +++ b/packages/runtime/tests/output-boundaries.test.ts @@ -23,6 +23,7 @@ async function sources(directory: string): Promise { // Adding a raw writer requires reviewing its format guard and documenting the exception. const nativeWrites = { "commands/app/call.ts": 1, + "commands/auth/aliyun.ts": 1, "commands/auth/login-console.ts": 1, "commands/knowledge/chat.ts": 3, "commands/managed-agent/_engine/playground-launcher.ts": 1, diff --git a/packages/runtime/tests/resolve.test.ts b/packages/runtime/tests/resolve.test.ts index 539127278..4ea362854 100644 --- a/packages/runtime/tests/resolve.test.ts +++ b/packages/runtime/tests/resolve.test.ts @@ -94,6 +94,28 @@ test("bare leaf commands with required flags show help, while supplied flags enf }); }); +test("hybrid commands show help with only global flags, but enforce required command flags", () => { + const hybrid = new CommandRegistry({ text: command, "text chat": command }, "bl"); + expect(resolve(["--config=work", "text", "--quiet"], hybrid)).toMatchObject({ + kind: "help", + path: ["text"], + parsedFlags: { config: "work", quiet: true }, + }); + expect(resolve(["--timeout=0", "text"], hybrid)).toMatchObject({ + kind: "usageError", + error: { exitCode: ExitCode.USAGE, message: expect.stringMatching(/timeout/i) }, + }); + expect(resolve(["text", "--api-key", "fake-key"], hybrid)).toMatchObject({ + kind: "usageError", + error: { exitCode: ExitCode.USAGE, message: "Missing required flag: --prompt" }, + }); + expect(resolve(["--config=work", "text", "--prompt", "hi"], hybrid)).toMatchObject({ + kind: "run", + path: ["text"], + parsedFlags: { config: "work", prompt: "hi" }, + }); +}); + test("global flags between command path segments are rejected", () => { expect(resolve(["text", "--config=work", "chat"], registry)).toMatchObject({ kind: "usageError", diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index 8c14550ff..68159aa14 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -19,12 +19,12 @@ Index: [index.md](index.md) ### `bl auth` -| Field | Value | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | -| **Name** | `auth` | -| **Description** | Authenticate with Aliyun OAuth | -| **Authentication** | No Auth | -| **Usage** | `bl auth --login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `auth` | +| **Description** | Authenticate with Aliyun OAuth | +| **Authentication** | No Auth | +| **Usage** | `bl auth --login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ] [--no-browser]` | #### Flags @@ -39,11 +39,11 @@ Index: [index.md](index.md) | `--console-gateway ` | string | no | Console gateway origin override (production default: https://bailian-cs.console.aliyun.com) | | `--bailiancontrol-host ` | string | no | Optional Bailian Control OpenAPI hostname | | `--console-region ` | string | no | Console region (only cn-beijing; default: cn-beijing) | -| `--no-browser` | switch | no | Do not open the browser automatically; still wait for the local callback | +| `--no-browser` | switch | no | Authorize on another device and paste the full callback URL; no local listener | #### Notes -- Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. No device flow or remote callback import is supported. +- Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. With --no-browser, paste the complete callback URL into this login session; this is not device authorization. - Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match. #### Examples @@ -52,6 +52,10 @@ Index: [index.md](index.md) bl auth --login aliyun --client-id --authorization-url ``` +```bash +bl auth --login aliyun --client-id --authorization-url --no-browser +``` + ```bash bl auth --login aliyun --client-id --authorization-url --modelstudio-host --console-gateway ``` From 8dcbe853cd8659cc452f5c9f63655eebfe9ab1b7 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Sat, 28 Nov 2026 21:36:00 +0800 Subject: [PATCH 05/13] feat(auth): move OAuth login to auth login --oauth with international site support Replace the beta-only `bl auth --login aliyun` root entry with a fourth login mode `bl auth login --oauth`, aligned with --console/--open-api. --console-site selects domestic/international; --console-region only sets the saved console_region and Console routing while OAuth endpoints follow the site alone. International pre-release ships the approved client ID with placeholder endpoints that block live login until confirmed; international production stays hard-blocked. Session fingerprints now include the console site, so existing beta sessions re-login once. --- packages/cli/src/commands.ts | 2 - .../src/commands/auth/aliyun-flags.ts | 70 +++++ packages/commands/src/commands/auth/aliyun.ts | 244 +++++++----------- .../commands/src/commands/auth/console-ui.ts | 5 +- packages/commands/src/commands/auth/login.ts | 108 ++++++-- packages/commands/src/commands/auth/status.ts | 3 +- packages/commands/src/index.ts | 1 - packages/core/src/auth/aliyun-config.ts | 11 + packages/core/src/auth/aliyun-types.ts | 2 + packages/core/src/auth/index.ts | 1 + packages/core/src/auth/openapi-provider.ts | 4 +- packages/core/src/auth/refresh-token.ts | 12 +- packages/core/src/auth/store.ts | 3 +- packages/core/src/config/control-plane.ts | 140 ++++++++-- packages/core/src/config/index.ts | 8 + packages/core/src/console/gateway.ts | 5 + packages/core/src/console/index.ts | 1 + packages/runtime/src/error-handler.ts | 2 +- skills/bailian-cli/reference/auth.md | 95 +++---- skills/bailian-cli/reference/index.md | 5 +- 20 files changed, 452 insertions(+), 270 deletions(-) create mode 100644 packages/commands/src/commands/auth/aliyun-flags.ts diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 685d738b0..6e438632a 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -1,7 +1,6 @@ import type { AnyCommand } from "bailian-cli-core"; import { deprecatedCommand } from "./deprecated.ts"; import { - authRoot, authLogin, authStatus, authLogout, @@ -413,7 +412,6 @@ import { // (no side effects) so tools like generate-reference.ts can import it without // starting the CLI. export const commands: Record = { - auth: authRoot, "auth login": authLogin, "auth status": authStatus, "auth logout": authLogout, diff --git a/packages/commands/src/commands/auth/aliyun-flags.ts b/packages/commands/src/commands/auth/aliyun-flags.ts new file mode 100644 index 000000000..2d8fc8758 --- /dev/null +++ b/packages/commands/src/commands/auth/aliyun-flags.ts @@ -0,0 +1,70 @@ +import { + ALIYUN_CLI_SCOPE, + ALIYUN_OAUTH_BASE_URL, + resolveConsoleGatewayOrigin, + resolveModelStudioHost, + type FlagsDef, +} from "bailian-cli-core"; + +const DOMESTIC_MODEL_STUDIO_HOST = resolveModelStudioHost("cn-beijing")!; +const DOMESTIC_CONSOLE_GATEWAY = resolveConsoleGatewayOrigin("cn-beijing", "domestic"); + +/** Aliyun OAuth specific flags shared by the `auth login --oauth` entry. */ +export const ALIYUN_OAUTH_LOGIN_FLAGS = { + clientId: { + type: "string", + valueHint: "", + description: { + "en-US": "OAuth client ID; required for the first login outside pre-release", + "zh-CN": "OAuth 客户端 ID;非预发环境首次登录必须提供", + }, + }, + scope: { + type: "string", + valueHint: "", + description: { + "en-US": `OAuth scope (default: ${ALIYUN_CLI_SCOPE})`, + "zh-CN": `OAuth 授权范围(默认:${ALIYUN_CLI_SCOPE})`, + }, + }, + oauthBaseUrl: { + type: "string", + valueHint: "", + description: { + "en-US": `OAuth token service origin (production default: ${ALIYUN_OAUTH_BASE_URL})`, + "zh-CN": `OAuth 令牌服务源站(线上默认:${ALIYUN_OAUTH_BASE_URL})`, + }, + }, + authorizationUrl: { + type: "string", + valueHint: "", + description: { + "en-US": "Explicit authorization URL; required for the first login outside pre-release", + "zh-CN": "显式授权地址;非预发环境首次登录必须提供", + }, + }, + modelstudioHost: { + type: "string", + valueHint: "", + description: { + "en-US": `Model Studio POP hostname override (domestic production default: ${DOMESTIC_MODEL_STUDIO_HOST})`, + "zh-CN": `Model Studio POP 主机名覆盖(国内线上默认:${DOMESTIC_MODEL_STUDIO_HOST})`, + }, + }, + consoleGateway: { + type: "string", + valueHint: "", + description: { + "en-US": `Console gateway origin override (domestic production default: ${DOMESTIC_CONSOLE_GATEWAY})`, + "zh-CN": `控制台网关源站覆盖(国内线上默认:${DOMESTIC_CONSOLE_GATEWAY})`, + }, + }, + bailiancontrolHost: { + type: "string", + valueHint: "", + description: { + "en-US": "Optional Bailian Control OpenAPI hostname", + "zh-CN": "可选 Bailian Control OpenAPI 主机名", + }, + }, +} satisfies FlagsDef; diff --git a/packages/commands/src/commands/auth/aliyun.ts b/packages/commands/src/commands/auth/aliyun.ts index e4d8cdeb1..ef0a799e3 100644 --- a/packages/commands/src/commands/auth/aliyun.ts +++ b/packages/commands/src/commands/auth/aliyun.ts @@ -10,27 +10,37 @@ import { PRE_ALIYUN_AUTHORIZATION_URL, PRE_ALIYUN_OAUTH_BASE_URL, PRE_BAILIAN_CONTROL_HOST, + PRE_INTL_ALIYUN_AUTHORIZATION_URL, + PRE_INTL_ALIYUN_CLI_CLIENT_ID, + PRE_INTL_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_BAILIAN_CONTROL_HOST, + PRE_INTL_MODEL_STUDIO_HOST, PRE_MODEL_STUDIO_HOST, UsageError, aliyunAuthorizationUrl, consoleCredentialKey, createOAuthProofKey, - defineCommand, + defaultConsoleRegion, exchangeAliyunCode, exchangeAliyunSts, generateCLIAccessToken, + intlPreEndpointsConfirmed, normalizeOAuthUrl, normalizeOpenApiHost, parseAliyunCallback, + profileSite, requirePreConsoleGateway, resolveConsoleGatewayOrigin, resolveModelStudioHost, revokeAliyunTokens, + unconfirmedIntlPreError, validateConsoleAccessToken, + validatePreConsoleRegion, type AliyunOAuthProfile, type AliyunOAuthSession, type AuthStore, type CommandOutput, + type ConsoleSite, type Identity, type LocalizedText, type Settings, @@ -58,6 +68,7 @@ export interface AliyunOAuthLoginOptions { modelstudioHost?: string; consoleGateway?: string; bailiancontrolHost?: string; + consoleSite?: ConsoleSite; consoleRegion?: string; noBrowser?: boolean; callbackTimeoutMs?: number; @@ -68,7 +79,6 @@ type LoginProfile = Omit; const CALLBACK_TIMEOUT_MS = 15 * 60 * 1000; const OAUTH_CALLBACK_PATH = "/oauth/callback"; const DEFAULT_MODEL_STUDIO_HOST = resolveModelStudioHost("cn-beijing")!; -const DEFAULT_CONSOLE_GATEWAY = resolveConsoleGatewayOrigin("cn-beijing", "domestic"); function localize(deps: AliyunOAuthLoginDeps, text: LocalizedText): string { return deps.localize ? deps.localize(text) : typeof text === "string" ? text : text["en-US"]; @@ -100,61 +110,91 @@ function loginPlan( previous?: AliyunOAuthProfile, ) { const pre = settings.preControlPlane; + const site: ConsoleSite = + options.consoleSite ?? previous?.console_site ?? settings.consoleSite ?? "domestic"; + // Saved metadata only applies to the same site; switching sites starts fresh. + const saved = previous && profileSite(previous) === site ? previous : undefined; const clientId = - options.clientId ?? previous?.client_id ?? (pre ? ALIYUN_CLI_CLIENT_ID : undefined); - const scope = nonempty(options.scope ?? previous?.scope ?? ALIYUN_CLI_SCOPE, "--scope"); + options.clientId ?? + saved?.client_id ?? + (pre + ? site === "international" + ? PRE_INTL_ALIYUN_CLI_CLIENT_ID + : ALIYUN_CLI_CLIENT_ID + : undefined); + const scope = nonempty(options.scope ?? saved?.scope ?? ALIYUN_CLI_SCOPE, "--scope"); const region = nonempty( options.consoleRegion ?? (pre && settings.consoleRegion) ?? - previous?.console_region ?? - "cn-beijing", + saved?.console_region ?? + defaultConsoleRegion(site), "--console-region", ); - if (region !== "cn-beijing" || (pre && previous && previous.console_region !== "cn-beijing")) { - throw new UsageError( - "Aliyun OAuth currently supports only cn-beijing. / 阿里云 OAuth 目前仅支持 cn-beijing。", - ); - } const normalizedClientId = clientId === undefined ? undefined : nonempty(clientId, "--client-id"); - const domains = { console_region: region, console_enabled: true, openapi_enabled: true }; + const domains = { + console_region: region, + ...(site === "international" ? { console_site: site } : {}), + console_enabled: true, + openapi_enabled: true, + }; if (pre) { - const target = { region, site: settings.consoleSite ?? "domestic" }; + validatePreConsoleRegion({ region, site }); + if (saved) validatePreConsoleRegion({ region: saved.console_region, site }); + const intlPending = site === "international" && !intlPreEndpointsConfirmed(); + // Live login must stop until the server side confirms the intl endpoints; + // dry-run stays offline and reports them as missing instead. + if (intlPending && !settings.dryRun) throw unconfirmedIntlPreError(); + const trusted = + site === "international" + ? { + authorizationUrl: PRE_INTL_ALIYUN_AUTHORIZATION_URL, + oauthBaseUrl: PRE_INTL_ALIYUN_OAUTH_BASE_URL, + modelstudioHost: PRE_INTL_MODEL_STUDIO_HOST, + bailiancontrolHost: PRE_INTL_BAILIAN_CONTROL_HOST, + } + : { + authorizationUrl: PRE_ALIYUN_AUTHORIZATION_URL, + oauthBaseUrl: PRE_ALIYUN_OAUTH_BASE_URL, + modelstudioHost: PRE_MODEL_STUDIO_HOST, + bailiancontrolHost: PRE_BAILIAN_CONTROL_HOST, + }; + const target = { region, site }; const gateway = - settings.dryRun && !pre.consoleGateway && target.site === "domestic" + intlPending || (settings.dryRun && !pre.consoleGateway) ? undefined : requirePreConsoleGateway(pre, target); const normalizeOrigin = (value: string) => normalizeOAuthUrl(value, true); trustedPreEndpoint( options.authorizationUrl, - previous?.authorization_url, - PRE_ALIYUN_AUTHORIZATION_URL, + saved?.authorization_url, + trusted.authorizationUrl, "--authorization-url", normalizeOAuthUrl, ); trustedPreEndpoint( options.oauthBaseUrl, - previous?.oauth_base_url, - PRE_ALIYUN_OAUTH_BASE_URL, + saved?.oauth_base_url, + trusted.oauthBaseUrl, "--oauth-base-url", normalizeOrigin, ); trustedPreEndpoint( options.modelstudioHost, - previous?.modelstudio_host, - PRE_MODEL_STUDIO_HOST, + saved?.modelstudio_host, + trusted.modelstudioHost, "--modelstudio-host", normalizeOpenApiHost, ); trustedPreEndpoint( options.bailiancontrolHost, - previous?.bailiancontrol_host, - PRE_BAILIAN_CONTROL_HOST, + saved?.bailiancontrol_host, + trusted.bailiancontrolHost, "--bailiancontrol-host", normalizeOpenApiHost, ); trustedPreEndpoint( options.consoleGateway, - previous?.console_gateway, + saved?.console_gateway, gateway, "--console-gateway", normalizeOrigin, @@ -162,25 +202,33 @@ function loginPlan( return { client_id: normalizedClientId, scope, - oauth_base_url: PRE_ALIYUN_OAUTH_BASE_URL, - authorization_url: PRE_ALIYUN_AUTHORIZATION_URL, - modelstudio_host: PRE_MODEL_STUDIO_HOST, + oauth_base_url: trusted.oauthBaseUrl, + authorization_url: trusted.authorizationUrl, + modelstudio_host: trusted.modelstudioHost, console_gateway: gateway, - bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + bailiancontrol_host: trusted.bailiancontrolHost, ...domains, }; } - const authorizationUrl = options.authorizationUrl ?? previous?.authorization_url; + if (site === "international") { + throw new UsageError( + "International production OAuth login is not available yet; the production application has not been approved. / 国际站线上 OAuth 登录尚未开放(线上应用未申请)。", + ); + } + const authorizationUrl = options.authorizationUrl ?? saved?.authorization_url; const modelstudioHost = - options.modelstudioHost ?? previous?.modelstudio_host ?? DEFAULT_MODEL_STUDIO_HOST; + options.modelstudioHost ?? + saved?.modelstudio_host ?? + resolveModelStudioHost(region) ?? + DEFAULT_MODEL_STUDIO_HOST; const consoleGateway = - options.consoleGateway ?? previous?.console_gateway ?? DEFAULT_CONSOLE_GATEWAY; - const bailiancontrolHost = options.bailiancontrolHost ?? previous?.bailiancontrol_host; + options.consoleGateway ?? saved?.console_gateway ?? resolveConsoleGatewayOrigin(region, site); + const bailiancontrolHost = options.bailiancontrolHost ?? saved?.bailiancontrol_host; return { client_id: normalizedClientId, scope, oauth_base_url: normalizeOAuthUrl( - options.oauthBaseUrl ?? previous?.oauth_base_url ?? ALIYUN_OAUTH_BASE_URL, + options.oauthBaseUrl ?? saved?.oauth_base_url ?? ALIYUN_OAUTH_BASE_URL, true, ), authorization_url: @@ -666,7 +714,10 @@ export async function runAliyunOAuthLogin( ...plan, client_id: plan.client_id, authorization_url: plan.authorization_url, - // The live preflight above requires a configured gateway; only dry-run may omit it. + // Live preflight above requires confirmed endpoints and a configured gateway; + // only dry-run may omit them. + oauth_base_url: plan.oauth_base_url!, + modelstudio_host: plan.modelstudio_host!, console_gateway: plan.console_gateway!, }; const cancellation = new AbortController(); @@ -695,8 +746,8 @@ export async function runAliyunOAuthLogin( assertActive(signal, deps); const settings: Settings = { ...deps.settings, - consoleRegion: "cn-beijing", - consoleSite: "domestic", + consoleRegion: profile.console_region, + consoleSite: profileSite(profile), consoleSwitchAgent: undefined, }; const { cliAccessToken } = await generateCLIAccessToken({ @@ -712,8 +763,8 @@ export async function runAliyunOAuthLogin( secrets.push(cliAccessToken); assertActive(signal, deps); const target = { - region: "cn-beijing", - site: "domestic" as const, + region: profile.console_region, + site: profileSite(profile), gateway: profile.console_gateway, }; await validateConsoleAccessToken({ ...target, token: cliAccessToken }, settings, { signal }); @@ -749,122 +800,3 @@ export async function runAliyunOAuthLogin( process.off("SIGTERM", onSignal); } } - -export default defineCommand({ - description: { "en-US": "Authenticate with Aliyun OAuth", "zh-CN": "通过阿里云 OAuth 登录" }, - auth: "none", - usageArgs: - "--login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ] [--no-browser]", - exampleArgs: [ - "--login aliyun --client-id --authorization-url ", - "--login aliyun --client-id --authorization-url --no-browser", - "--login aliyun --client-id --authorization-url --modelstudio-host --console-gateway ", - ], - flags: { - login: { - type: "string", - required: true, - choices: ["aliyun"] as const, - valueHint: "", - description: { "en-US": "Login method: aliyun", "zh-CN": "登录方式:aliyun" }, - }, - clientId: { - type: "string", - valueHint: "", - description: { - "en-US": "OAuth client ID; required for the first login outside pre-release", - "zh-CN": "OAuth 客户端 ID;非预发环境首次登录必须提供", - }, - }, - scope: { - type: "string", - valueHint: "", - description: { - "en-US": `OAuth scope (default: ${ALIYUN_CLI_SCOPE})`, - "zh-CN": `OAuth 授权范围(默认:${ALIYUN_CLI_SCOPE})`, - }, - }, - oauthBaseUrl: { - type: "string", - valueHint: "", - description: { - "en-US": `OAuth token service origin (production default: ${ALIYUN_OAUTH_BASE_URL})`, - "zh-CN": `OAuth 令牌服务源站(线上默认:${ALIYUN_OAUTH_BASE_URL})`, - }, - }, - authorizationUrl: { - type: "string", - valueHint: "", - description: { - "en-US": "Explicit authorization URL; required for the first login outside pre-release", - "zh-CN": "显式授权地址;非预发环境首次登录必须提供", - }, - }, - modelstudioHost: { - type: "string", - valueHint: "", - description: { - "en-US": `Model Studio POP hostname override (production default: ${DEFAULT_MODEL_STUDIO_HOST})`, - "zh-CN": `Model Studio POP 主机名覆盖(线上默认:${DEFAULT_MODEL_STUDIO_HOST})`, - }, - }, - consoleGateway: { - type: "string", - valueHint: "", - description: { - "en-US": `Console gateway origin override (production default: ${DEFAULT_CONSOLE_GATEWAY})`, - "zh-CN": `控制台网关源站覆盖(线上默认:${DEFAULT_CONSOLE_GATEWAY})`, - }, - }, - bailiancontrolHost: { - type: "string", - valueHint: "", - description: { - "en-US": "Optional Bailian Control OpenAPI hostname", - "zh-CN": "可选 Bailian Control OpenAPI 主机名", - }, - }, - consoleRegion: { - type: "string", - choices: ["cn-beijing"] as const, - valueHint: "", - description: { - "en-US": "Console region (only cn-beijing; default: cn-beijing)", - "zh-CN": "控制台地域(仅支持 cn-beijing;默认:cn-beijing)", - }, - }, - noBrowser: { - type: "switch", - description: { - "en-US": "Authorize on another device and paste the full callback URL; no local listener", - "zh-CN": "在其它设备授权后粘贴完整回调 URL;不监听本地端口", - }, - }, - }, - notes: [ - { - "en-US": - "Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. With --no-browser, paste the complete callback URL into this login session; this is not device authorization.", - "zh-CN": - "非预发环境首次登录需要显式指定客户端 ID 和已确认的授权地址。预发端点覆盖必须与可信端点一致,并且必须配置 CLI 网关。使用 --no-browser 时须在本次登录会话中粘贴完整回调 URL;这不是设备授权。", - }, - { - "en-US": - "Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match.", - "zh-CN": - "IAM 重定向 URI 登记为 http://127.0.0.1:12345/oauth/callback。NativeApp 回环端口可随机,协议、主机和路径必须一致。", - }, - ], - async run(ctx) { - await runAliyunOAuthLogin( - { - identity: ctx.identity, - settings: ctx.settings, - authStore: ctx.authStore, - output: ctx.output, - localize: ctx.localize, - }, - ctx.flags, - ); - }, -}); diff --git a/packages/commands/src/commands/auth/console-ui.ts b/packages/commands/src/commands/auth/console-ui.ts index 71b385055..5c469ab99 100644 --- a/packages/commands/src/commands/auth/console-ui.ts +++ b/packages/commands/src/commands/auth/console-ui.ts @@ -1,5 +1,6 @@ import { maskToken, + profileSite, type AuthStore, type CommandOutput, type Identity, @@ -82,7 +83,9 @@ export function makeAuthUiBridge(ctx: { region: a.console?.region ?? (a.aliyunOAuth?.console_enabled ? a.aliyunOAuth.console_region : undefined), - site: a.console?.site ?? (a.aliyunOAuth?.console_enabled ? "domestic" : undefined), + site: + a.console?.site ?? + (a.aliyunOAuth?.console_enabled ? profileSite(a.aliyunOAuth) : undefined), masked, }; }, diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index 812b1df27..6c002827b 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -14,6 +14,8 @@ import { type Settings, } from "bailian-cli-core"; import { persistApiKey, validateApiKey } from "./login-api-key.ts"; +import { runAliyunOAuthLogin } from "./aliyun.ts"; +import { ALIYUN_OAUTH_LOGIN_FLAGS } from "./aliyun-flags.ts"; import { resolveConsoleLoginTarget, runConsoleLogin, @@ -21,7 +23,8 @@ import { } 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"; +const LOGIN_MODE_HINT = + "Choose exactly one login mode: --api-key, --console, --open-api, or --oauth. / 请恰好选择一种登录方式:--api-key、--console、--open-api 或 --oauth。"; function hasValue(value: unknown): value is string { return typeof value === "string" && value.trim().length > 0; @@ -59,12 +62,13 @@ function previewPreLogin( export default defineCommand({ description: { "en-US": - "Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist)", - "zh-CN": "使用 API Key、控制台浏览器登录或 OpenAPI AK/SK 进行认证(多种凭证可共存)", + "Authenticate with API key, console browser login, OpenAPI AK/SK, or Aliyun OAuth (credentials can coexist)", + "zh-CN": + "使用 API Key、控制台浏览器登录、OpenAPI AK/SK 或阿里云 OAuth 进行认证(多种凭证可共存)", }, auth: "none", usageArgs: - "--api-key | --console [--no-browser | --token-stdin --console-region ] | --open-api [--no-browser] [--console-site ] [--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 ] | --oauth [--console-site ] [--console-region ] [--no-browser]", flags: { apiKey: { type: "string", @@ -95,8 +99,9 @@ export default defineCommand({ type: "switch", description: { "en-US": - "With --console or --open-api (setup guide), print the URL without opening a browser", - "zh-CN": "与 --console 或 --open-api(配置引导)一起使用,只打印地址,不自动打开浏览器", + "With --console or --open-api (setup guide), print the URL without opening a browser; with --oauth, authorize on another device and paste the full callback URL (no local listener)", + "zh-CN": + "与 --console 或 --open-api(配置引导)一起使用,只打印地址,不自动打开浏览器;与 --oauth 一起使用,在其它设备授权后粘贴完整回调 URL,不监听本地端口", }, }, tokenStdin: { @@ -130,6 +135,16 @@ export default defineCommand({ "打开 AccessKey 配置引导;同时提供 --access-key-id 与 --access-key-secret 时则校验并保存", }, }, + oauth: { + type: "switch", + description: { + "en-US": + "Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a 30-day console session with automatic renewal", + "zh-CN": + "通过阿里云 OAuth 登录(默认中国站;国际站使用 --console-site international)。换取 30 天控制台会话并自动续期", + }, + }, + ...ALIYUN_OAUTH_LOGIN_FLAGS, accessKeyId: { type: "string", valueHint: "", @@ -156,22 +171,41 @@ export default defineCommand({ "--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", + "--oauth", + "--oauth --console-site international", + "--oauth --no-browser", + ], + notes: [ + { + "en-US": + "With --oauth outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. With --no-browser, paste the complete callback URL into this login session; this is not device authorization.", + "zh-CN": + "--oauth 在非预发环境首次登录需要显式指定客户端 ID 和已确认的授权地址。预发端点覆盖必须与可信端点一致,并且必须配置 CLI 网关。使用 --no-browser 时须在本次登录会话中粘贴完整回调 URL;这不是设备授权。", + }, + { + "en-US": + "Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match.", + "zh-CN": + "IAM 重定向 URI 登记为 http://127.0.0.1:12345/oauth/callback。NativeApp 回环端口可随机,协议、主机和路径必须一致。", + }, ], validate: (flags) => { const apiKeyMode = hasValue(flags.apiKey); const consoleMode = flags.console === true; const openApiMode = flags.openApi === true; + const oauthMode = flags.oauth === true; const openApiHasId = hasValue(flags.accessKeyId); const openApiHasSecret = hasValue(flags.accessKeySecret); const openApiPersist = openApiMode && openApiHasId && openApiHasSecret; - 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.tokenStdin && !consoleMode) { + return "Use --token-stdin only with --console. / --token-stdin 只能与 --console 一起使用。"; } - if (flags.noBrowser && !consoleMode && !openApiMode) { - return "Use --no-browser with --console or --open-api. / --no-browser 只能与 --console 或 --open-api 一起使用。"; + if (hasValue(flags.consoleRegion) && !consoleMode && !oauthMode) { + return "Use --console-region only with --console or --oauth. / --console-region 只能与 --console 或 --oauth 一起使用。"; + } + if (flags.noBrowser && !consoleMode && !openApiMode && !oauthMode) { + return "Use --no-browser with --console, --open-api, or --oauth. / --no-browser 只能与 --console、--open-api 或 --oauth 一起使用。"; } if (flags.noBrowser && flags.tokenStdin) { return "Choose either --no-browser or --token-stdin. / --no-browser 与 --token-stdin 不能同时使用。"; @@ -179,8 +213,8 @@ export default defineCommand({ if (flags.tokenStdin && !hasValue(flags.consoleRegion)) { return "Provide --console-region with --token-stdin. / 使用 --token-stdin 时必须指定 --console-region。"; } - if (!flags.tokenStdin && hasValue(flags.consoleRegion)) { - return "Use --console-region only with --console --token-stdin. / --console-region 只能与 --console --token-stdin 一起使用。"; + if (!flags.tokenStdin && !oauthMode && hasValue(flags.consoleRegion)) { + return "Use --console-region only with --console --token-stdin or --oauth. / --console-region 只能与 --console --token-stdin 或 --oauth 一起使用。"; } // Mode-specific options must not imply a login mode by themselves; this keeps @@ -188,8 +222,25 @@ export default defineCommand({ if (!apiKeyMode && hasValue(flags.baseUrl)) { return "Use --base-url only with --api-key"; } - if (hasValue(flags.consoleSite) && !consoleMode && !openApiMode) { - return "Use --console-site with --console or --open-api. / --console-site 只能与 --console 或 --open-api 一起使用。"; + if (hasValue(flags.consoleSite) && !consoleMode && !openApiMode && !oauthMode) { + return "Use --console-site with --console, --open-api, or --oauth. / --console-site 只能与 --console、--open-api 或 --oauth 一起使用。"; + } + const oauthOnlyFlags = [ + ["clientId", "--client-id"], + ["scope", "--scope"], + ["oauthBaseUrl", "--oauth-base-url"], + ["authorizationUrl", "--authorization-url"], + ["modelstudioHost", "--modelstudio-host"], + ["consoleGateway", "--console-gateway"], + ["bailiancontrolHost", "--bailiancontrol-host"], + ] as const; + for (const [flagName, flagLabel] of oauthOnlyFlags) { + if (!oauthMode && hasValue(flags[flagName])) { + return `Use ${flagLabel} only with --oauth. / ${flagLabel} 只能与 --oauth 一起使用。`; + } + } + if (oauthMode && (flags.tokenStdin || hasValue(flags.baseUrl))) { + return "--oauth cannot be combined with --token-stdin or --base-url. / --oauth 不能与 --token-stdin 或 --base-url 同时使用。"; } if (!openApiMode && (openApiHasId || openApiHasSecret)) { return "Use --open-api with --access-key-id and --access-key-secret"; @@ -200,7 +251,7 @@ export default defineCommand({ // 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; + const modeCount = [apiKeyMode, consoleMode, openApiMode, oauthMode].filter(Boolean).length; if (modeCount !== 1) return LOGIN_MODE_HINT; // AK/SK are a credential pair. Persist only what the user typed; guide when neither half is set. @@ -235,6 +286,25 @@ export default defineCommand({ const key = flags.apiKey; const baseUrl = flags.baseUrl ? normalizeModelBaseUrl(flags.baseUrl) : undefined; + if (flags.oauth) { + await runAliyunOAuthLogin(deps, { + clientId: flags.clientId, + scope: flags.scope, + oauthBaseUrl: flags.oauthBaseUrl, + authorizationUrl: flags.authorizationUrl, + modelstudioHost: flags.modelstudioHost, + consoleGateway: flags.consoleGateway, + bailiancontrolHost: flags.bailiancontrolHost, + // Explicit Console site wins over the selected Profile; the whole exchange uses it. + consoleSite: (flags.consoleSite || settings.consoleSite || "domestic") as + | "domestic" + | "international", + consoleRegion: flags.consoleRegion, + noBrowser: flags.noBrowser, + }); + return; + } + if (flags.console) { // Explicit Console site wins over the selected Profile; all requests use this target. const consoleSettings: Settings = { @@ -330,9 +400,9 @@ export default defineCommand({ throw new BailianError( ctx.localize({ "en-US": - "The AccessKey browser guide is only available online. In pre-release, provide --access-key-id and --access-key-secret, or use auth --login aliyun.", + "The AccessKey browser guide is only available online. In pre-release, provide --access-key-id and --access-key-secret, or use auth login --oauth.", "zh-CN": - "AccessKey 浏览器引导仅支持线上。预发请提供 --access-key-id 和 --access-key-secret,或使用 auth --login aliyun。", + "AccessKey 浏览器引导仅支持线上。预发请提供 --access-key-id 和 --access-key-secret,或使用 auth login --oauth。", }), ExitCode.USAGE, ); diff --git a/packages/commands/src/commands/auth/status.ts b/packages/commands/src/commands/auth/status.ts index 85000a4f2..f4be4788b 100644 --- a/packages/commands/src/commands/auth/status.ts +++ b/packages/commands/src/commands/auth/status.ts @@ -4,6 +4,7 @@ import { formatCommand, formatText, maskToken, + profileSite, } from "bailian-cli-core"; import { API_KEY_PAGE } from "bailian-cli-runtime"; @@ -48,7 +49,7 @@ export default defineCommand({ source: "config", method: "aliyun", region: auth.aliyunOAuth.console_region, - site: "domestic", + site: profileSite(auth.aliyunOAuth), } : undefined; const openapi = auth.openapi diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index 676258f84..c0c9351b2 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -3,7 +3,6 @@ // entrypoint (bl / rag / …) builds its own `{ "": command }` map, so the // command paths a product exposes are a product decision, not baked in here. -export { default as authRoot } from "./commands/auth/aliyun.ts"; export { default as authLogin } from "./commands/auth/login.ts"; export { default as authStatus } from "./commands/auth/status.ts"; export { default as authLogout } from "./commands/auth/logout.ts"; diff --git a/packages/core/src/auth/aliyun-config.ts b/packages/core/src/auth/aliyun-config.ts index 3ee933835..528af97a3 100644 --- a/packages/core/src/auth/aliyun-config.ts +++ b/packages/core/src/auth/aliyun-config.ts @@ -1,10 +1,16 @@ import { UsageError } from "../errors/base.ts"; import type { AliyunOAuthProfile } from "./aliyun-types.ts"; +import type { ConsoleSite } from "../console/gateway.ts"; export const ALIYUN_CLI_CLIENT_ID = "4001958595402383681"; export const ALIYUN_CLI_SCOPE = "openid /internal/bailian/cli"; export const ALIYUN_OAUTH_BASE_URL = "https://oauth.aliyun.com"; +/** Profiles saved before international support carry no console_site; they are domestic. */ +export function profileSite(profile: Pick): ConsoleSite { + return profile.console_site ?? "domestic"; +} + export function normalizeOAuthUrl(value: string, originOnly = false): string { let url: URL; try { @@ -98,6 +104,11 @@ export function parseAliyunOAuthProfile(raw: unknown): AliyunOAuthProfile { throw new UsageError("Invalid bailiancontrol_host. / bailiancontrol_host 无效。"); result.bailiancontrol_host = normalizeOpenApiHost(profile.bailiancontrol_host); } + if (profile.console_site !== undefined) { + if (profile.console_site !== "domestic" && profile.console_site !== "international") + throw new UsageError("Invalid aliyun_oauth.console_site. / aliyun_oauth.console_site 无效。"); + result.console_site = profile.console_site; + } for (const field of ["access_token_expires_at", "sts_expires_at"] as const) { const value = profile[field]; if (value !== undefined) { diff --git a/packages/core/src/auth/aliyun-types.ts b/packages/core/src/auth/aliyun-types.ts index b6d2ab512..f0fb9a120 100644 --- a/packages/core/src/auth/aliyun-types.ts +++ b/packages/core/src/auth/aliyun-types.ts @@ -1,4 +1,5 @@ import type { ConsoleCredential, OpenApiCredential } from "./types.ts"; +import type { ConsoleSite } from "../console/gateway.ts"; export interface AliyunOAuthProfile { client_id: string; @@ -9,6 +10,7 @@ export interface AliyunOAuthProfile { bailiancontrol_host?: string; console_gateway: string; console_region: string; + console_site?: ConsoleSite; session_ref: string; console_enabled: boolean; openapi_enabled: boolean; diff --git a/packages/core/src/auth/index.ts b/packages/core/src/auth/index.ts index 51ce3893f..4030a82f7 100644 --- a/packages/core/src/auth/index.ts +++ b/packages/core/src/auth/index.ts @@ -24,6 +24,7 @@ export { normalizeOAuthUrl, normalizeOpenApiHost, parseAliyunOAuthProfile, + profileSite, } from "./aliyun-config.ts"; export { createOAuthProofKey, diff --git a/packages/core/src/auth/openapi-provider.ts b/packages/core/src/auth/openapi-provider.ts index 68316c1e1..f3431ef03 100644 --- a/packages/core/src/auth/openapi-provider.ts +++ b/packages/core/src/auth/openapi-provider.ts @@ -13,6 +13,7 @@ import { withFileLock } from "../utils/file-lock.ts"; import { resolveOpenApi } from "./resolver.ts"; import { createOAuthSecretStore, type OAuthSecretStore } from "./secure-store.ts"; import { exchangeAliyunSts, refreshAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; +import { profileSite } from "./aliyun-config.ts"; import type { AliyunOAuthProfile, AliyunOAuthSession, @@ -37,6 +38,7 @@ export function oauthConfigurationFingerprint( profile.bailiancontrol_host ?? null, profile.console_gateway, profile.console_region, + profile.console_site ?? "domestic", ]), ) .digest("hex"); @@ -285,7 +287,7 @@ export function createOpenApiCredentialProvider( const gateway = pre ? requirePreConsoleGateway(pre, target) : profile.console_gateway; if ( target.region !== profile.console_region || - target.site !== "domestic" || + target.site !== profileSite(profile) || gateway !== profile.console_gateway || (target.gateway !== undefined && target.gateway !== profile.console_gateway) ) diff --git a/packages/core/src/auth/refresh-token.ts b/packages/core/src/auth/refresh-token.ts index 9e30b9a47..351a6f55a 100644 --- a/packages/core/src/auth/refresh-token.ts +++ b/packages/core/src/auth/refresh-token.ts @@ -3,7 +3,11 @@ import type { Identity, Settings } from "../config/schema.ts"; import { validatePreConsoleScope } from "../config/control-plane.ts"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; -import { callConsoleGateway, type ConsoleGatewayTarget } from "../console/gateway.ts"; +import { + callConsoleGateway, + defaultConsoleRegion, + type ConsoleGatewayTarget, +} from "../console/gateway.ts"; import { readConfigFile, mutateConfigFile } from "../config/loader.ts"; import { getConfigPath } from "../config/paths.ts"; import { Client } from "../client/client.ts"; @@ -31,8 +35,10 @@ export function resolveCLIAccessTokenTarget( baseUrl: string, ): Omit { if (settings.preControlPlane) { - validatePreConsoleScope({ region: settings.consoleRegion, site: settings.consoleSite }); - return { region: "cn-beijing", site: "domestic", switchAgent: settings.consoleSwitchAgent }; + const site = settings.consoleSite ?? "domestic"; + const region = settings.consoleRegion ?? defaultConsoleRegion(site); + validatePreConsoleScope({ region, site }); + return { region, site, switchAgent: settings.consoleSwitchAgent }; } let region = settings.consoleRegion; if (!region) { diff --git a/packages/core/src/auth/store.ts b/packages/core/src/auth/store.ts index 35aa95965..f74a98964 100644 --- a/packages/core/src/auth/store.ts +++ b/packages/core/src/auth/store.ts @@ -12,6 +12,7 @@ import { assertOAuthConfiguration, } from "./openapi-provider.ts"; import { revokeAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; +import { profileSite } from "./aliyun-config.ts"; import type { AliyunOAuthProfile, AliyunOAuthSession } from "./aliyun-types.ts"; import { CredentialError } from "../errors/credential.ts"; import { getConfigPath } from "../config/paths.ts"; @@ -185,7 +186,7 @@ export function makeAuthStore( ...current, aliyun_oauth: metadata, console_region: profile.console_region, - console_site: "domestic", + console_site: profileSite(profile), console_switch_agent: undefined, }; }, diff --git a/packages/core/src/config/control-plane.ts b/packages/core/src/config/control-plane.ts index 0f4523427..6a5adc460 100644 --- a/packages/core/src/config/control-plane.ts +++ b/packages/core/src/config/control-plane.ts @@ -1,4 +1,4 @@ -import { normalizeOAuthUrl } from "../auth/aliyun-config.ts"; +import { normalizeOAuthUrl, profileSite } from "../auth/aliyun-config.ts"; import type { AliyunOAuthProfile } from "../auth/aliyun-types.ts"; import { UsageError } from "../errors/base.ts"; @@ -10,6 +10,64 @@ export const PRE_BAILIAN_CONTROL_HOST = "bailiancontrol-pre.aliyuncs.com"; const PRE_CONSOLE_ORIGIN = "https://pre-bailian.console.aliyun.com"; const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; +// International pre-release endpoints stay undefined until the server side +// confirms them; never derive them from the domestic naming pattern. +export const PRE_INTL_ALIYUN_AUTHORIZATION_URL: string | undefined = undefined; +export const PRE_INTL_ALIYUN_OAUTH_BASE_URL: string | undefined = undefined; +export const PRE_INTL_MODEL_STUDIO_HOST: string | undefined = undefined; +export const PRE_INTL_BAILIAN_CONTROL_HOST: string | undefined = undefined; +const PRE_INTL_CONSOLE_ORIGIN: string | undefined = undefined; +const PRE_INTL_CONSOLE_GATEWAY: string | undefined = undefined; + +export const PRE_INTL_ALIYUN_CLI_CLIENT_ID = "4102369295402391842"; + +interface PreSiteGroup { + region: string; + authorizationUrl: string | undefined; + oauthBaseUrl: string | undefined; + modelStudioHost: string | undefined; + bailiancontrolHost: string | undefined; + consoleOrigin: string | undefined; + consoleGateway: string | undefined; +} + +const PRE_DOMESTIC_GROUP: PreSiteGroup = { + region: "cn-beijing", + authorizationUrl: PRE_ALIYUN_AUTHORIZATION_URL, + oauthBaseUrl: PRE_ALIYUN_OAUTH_BASE_URL, + modelStudioHost: PRE_MODEL_STUDIO_HOST, + bailiancontrolHost: PRE_BAILIAN_CONTROL_HOST, + consoleOrigin: PRE_CONSOLE_ORIGIN, + consoleGateway: PRE_CONSOLE_GATEWAY, +}; + +const PRE_INTL_GROUP: PreSiteGroup = { + region: "ap-southeast-1", + authorizationUrl: PRE_INTL_ALIYUN_AUTHORIZATION_URL, + oauthBaseUrl: PRE_INTL_ALIYUN_OAUTH_BASE_URL, + modelStudioHost: PRE_INTL_MODEL_STUDIO_HOST, + bailiancontrolHost: PRE_INTL_BAILIAN_CONTROL_HOST, + consoleOrigin: PRE_INTL_CONSOLE_ORIGIN, + consoleGateway: PRE_INTL_CONSOLE_GATEWAY, +}; + +export function intlPreEndpointsConfirmed(): boolean { + return ( + PRE_INTL_GROUP.authorizationUrl !== undefined && + PRE_INTL_GROUP.oauthBaseUrl !== undefined && + PRE_INTL_GROUP.modelStudioHost !== undefined && + PRE_INTL_GROUP.bailiancontrolHost !== undefined && + PRE_INTL_GROUP.consoleOrigin !== undefined && + PRE_INTL_GROUP.consoleGateway !== undefined + ); +} + +export function unconfirmedIntlPreError(): UsageError { + return new UsageError( + "International pre-release endpoints are not confirmed yet. / 国际站预发端点尚未确认,暂不可用。", + ); +} + export interface PreControlPlane { consoleOrigin?: string; consoleGateway?: string; @@ -34,41 +92,64 @@ export function resolvePreControlPlane(env: NodeJS.ProcessEnv): PreControlPlane return settings; } -export function validatePreConsoleScope(target: { region?: string; site?: string }): void { - if ( - (target.region !== undefined && target.region !== "cn-beijing") || - (target.site !== undefined && target.site !== "domestic") - ) { +/** Site×region combination check only; does not require confirmed intl endpoints. */ +export function validatePreConsoleRegion(target: { region?: string; site?: string }): void { + const site = target.site ?? "domestic"; + const group = + site === "international" + ? PRE_INTL_GROUP + : site === "domestic" + ? PRE_DOMESTIC_GROUP + : undefined; + if (!group || (target.region !== undefined && target.region !== group.region)) { throw new UsageError( - "The pre-release control plane supports only the domestic cn-beijing site. / 预发控制面当前仅支持国内站 cn-beijing。", + "The pre-release control plane supports domestic cn-beijing and international ap-southeast-1 only. / 预发控制面仅支持国内站 cn-beijing 与国际站 ap-southeast-1。", ); } } -export function requirePreConsoleOrigin( +export function validatePreConsoleScope(target: { region?: string; site?: string }): void { + validatePreConsoleRegion(target); + if ((target.site ?? "domestic") === "international" && !intlPreEndpointsConfirmed()) { + throw unconfirmedIntlPreError(); + } +} + +function requirePreEndpoint( pre: PreControlPlane, target: { region?: string; site?: string }, + kind: "consoleOrigin" | "consoleGateway", ): string { validatePreConsoleScope(target); - if (pre.consoleOrigin !== PRE_CONSOLE_ORIGIN) { + const group = target.site === "international" ? PRE_INTL_GROUP : PRE_DOMESTIC_GROUP; + const trusted = group[kind]; + const configured = pre[kind]; + if (trusted === undefined || configured !== trusted) { + const flag = + kind === "consoleOrigin" ? "BAILIAN_PRE_CONSOLE_ORIGIN" : "BAILIAN_PRE_CONSOLE_GATEWAY"; + const subject = kind === "consoleOrigin" ? "Console login origin" : "CLI gateway"; + const subjectZh = kind === "consoleOrigin" ? "控制台登录源站" : "CLI 网关"; + const siteLabel = target.site === "international" ? "international" : "domestic"; + const siteLabelZh = target.site === "international" ? "国际站" : "国内站"; throw new UsageError( - "Set BAILIAN_PRE_CONSOLE_ORIGIN to the confirmed domestic pre-release Console login origin. / 请将 BAILIAN_PRE_CONSOLE_ORIGIN 设为已确认的国内预发控制台登录源站。", + `Set ${flag} to the confirmed ${siteLabel} pre-release ${subject}. / 请将 ${flag} 设为已确认的${siteLabelZh}预发${subjectZh}。`, ); } - return pre.consoleOrigin; + return configured; +} + +export function requirePreConsoleOrigin( + pre: PreControlPlane, + target: { region?: string; site?: string }, +): string { + return requirePreEndpoint(pre, target, "consoleOrigin"); } export function requirePreConsoleGateway( pre: PreControlPlane, target: { region?: string; site?: string }, ): string { - validatePreConsoleScope(target); - if (pre.consoleGateway !== PRE_CONSOLE_GATEWAY) { - throw new UsageError( - "Set BAILIAN_PRE_CONSOLE_GATEWAY to the confirmed domestic pre-release CLI gateway. / 请将 BAILIAN_PRE_CONSOLE_GATEWAY 设为已确认的国内预发 CLI 网关。", - ); - } - return pre.consoleGateway; + return requirePreEndpoint(pre, target, "consoleGateway"); } export function resolvePreOpenApiHost(host: string): string { @@ -82,6 +163,15 @@ export function resolvePreOpenApiHost(host: string): string { case PRE_BAILIAN_CONTROL_HOST: return PRE_BAILIAN_CONTROL_HOST; default: + if ( + PRE_INTL_MODEL_STUDIO_HOST !== undefined && + (host === "modelstudio.ap-southeast-1.aliyuncs.com" || host === PRE_INTL_MODEL_STUDIO_HOST) + ) { + return PRE_INTL_MODEL_STUDIO_HOST; + } + if (PRE_INTL_BAILIAN_CONTROL_HOST !== undefined && host === PRE_INTL_BAILIAN_CONTROL_HOST) { + return PRE_INTL_BAILIAN_CONTROL_HOST; + } throw new UsageError( "This OpenAPI endpoint is not available in the pre-release control plane. / 此 OpenAPI 端点在预发控制面不可用。", ); @@ -89,14 +179,16 @@ export function resolvePreOpenApiHost(host: string): string { } export function validatePreAliyunProfile(profile: Omit): void { - validatePreConsoleScope({ region: profile.console_region }); + const site = profileSite(profile); + validatePreConsoleScope({ region: profile.console_region, site }); + const group = site === "international" ? PRE_INTL_GROUP : PRE_DOMESTIC_GROUP; if ( - profile.authorization_url !== PRE_ALIYUN_AUTHORIZATION_URL || - profile.oauth_base_url !== PRE_ALIYUN_OAUTH_BASE_URL || - profile.modelstudio_host !== PRE_MODEL_STUDIO_HOST || + profile.authorization_url !== group.authorizationUrl || + profile.oauth_base_url !== group.oauthBaseUrl || + profile.modelstudio_host !== group.modelStudioHost || (profile.bailiancontrol_host !== undefined && - profile.bailiancontrol_host !== PRE_BAILIAN_CONTROL_HOST) || - profile.console_gateway !== PRE_CONSOLE_GATEWAY + profile.bailiancontrol_host !== group.bailiancontrolHost) || + profile.console_gateway !== group.consoleGateway ) { throw new UsageError( "Aliyun OAuth profile endpoints do not match the pre-release control plane. / 阿里云 OAuth 配置端点与预发控制面不匹配。", diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.ts index 31a9e83dc..8ab7c12e1 100644 --- a/packages/core/src/config/index.ts +++ b/packages/core/src/config/index.ts @@ -59,10 +59,18 @@ export { PRE_ALIYUN_OAUTH_BASE_URL, PRE_MODEL_STUDIO_HOST, PRE_BAILIAN_CONTROL_HOST, + PRE_INTL_ALIYUN_AUTHORIZATION_URL, + PRE_INTL_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_MODEL_STUDIO_HOST, + PRE_INTL_BAILIAN_CONTROL_HOST, + PRE_INTL_ALIYUN_CLI_CLIENT_ID, requirePreConsoleGateway, requirePreConsoleOrigin, resolvePreControlPlane, resolvePreOpenApiHost, validatePreConsoleScope, + validatePreConsoleRegion, + intlPreEndpointsConfirmed, + unconfirmedIntlPreError, type PreControlPlane, } from "./control-plane.ts"; diff --git a/packages/core/src/console/gateway.ts b/packages/core/src/console/gateway.ts index 184c317a6..c2730cdca 100644 --- a/packages/core/src/console/gateway.ts +++ b/packages/core/src/console/gateway.ts @@ -44,6 +44,11 @@ function resolveGateway(region: string, site: ConsoleSite): ConsoleGatewayInfo { return REGION_GATEWAYS[region]?.[site] ?? REGION_GATEWAYS["cn-beijing"]![site]; } +/** Region default follows the site; an explicit --console-region may override it. */ +export function defaultConsoleRegion(site: ConsoleSite): string { + return site === "international" ? "ap-southeast-1" : "cn-beijing"; +} + export function resolveConsoleGatewayOrigin( region: string, site: ConsoleSite, diff --git a/packages/core/src/console/index.ts b/packages/core/src/console/index.ts index eede7d4e2..bd1f499b0 100644 --- a/packages/core/src/console/index.ts +++ b/packages/core/src/console/index.ts @@ -8,6 +8,7 @@ export type { export { anonymousConsoleCall, callConsoleGateway, + defaultConsoleRegion, effectiveConsoleGatewayConfig, resolveConsoleGatewayOrigin, } from "./gateway.ts"; diff --git a/packages/runtime/src/error-handler.ts b/packages/runtime/src/error-handler.ts index dda772f41..239851bad 100644 --- a/packages/runtime/src/error-handler.ts +++ b/packages/runtime/src/error-handler.ts @@ -60,7 +60,7 @@ export function aliyunRecoveryHint( configName?: string, localize: Localize = english, ): string { - const command = recoveryCommand(commandPrefix, "auth --login aliyun", configName); + const command = recoveryCommand(commandPrefix, "auth login --oauth", configName); return localize({ "en-US": `Run \`${command}\` to sign in to Aliyun again.`, "zh-CN": `请运行 \`${command}\` 重新登录阿里云。`, diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index 68159aa14..029ea3254 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -7,59 +7,15 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Authentication | Description | -| ------------------------------- | -------------- | -------------------------------------------------------------------------------------------- | -| `bl auth` | No Auth | Authenticate with Aliyun OAuth | -| `bl auth generate-access-token` | AK/SK | Generate a CLI access token using OpenAPI credentials | -| `bl auth login` | No Auth | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | -| `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | -| `bl auth status` | No Auth | Show current authentication state | +| Command | Authentication | Description | +| ------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- | +| `bl auth generate-access-token` | AK/SK | Generate a CLI access token using OpenAPI credentials | +| `bl auth login` | No Auth | Authenticate with API key, console browser login, OpenAPI AK/SK, or Aliyun OAuth (credentials can coexist) | +| `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | +| `bl auth status` | No Auth | Show current authentication state | ## Command details -### `bl auth` - -| Field | Value | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `auth` | -| **Description** | Authenticate with Aliyun OAuth | -| **Authentication** | No Auth | -| **Usage** | `bl auth --login aliyun [--client-id ] [--authorization-url ] [--modelstudio-host ] [--console-gateway ] [--no-browser]` | - -#### Flags - -| Flag | Type | Required | Description | -| ---------------------------------- | ------ | -------- | -------------------------------------------------------------------------------------------- | -| `--login ` | string | yes | Login method: aliyun | -| `--client-id ` | string | no | OAuth client ID; required for the first login outside pre-release | -| `--scope ` | string | no | OAuth scope (default: openid /internal/bailian/cli) | -| `--oauth-base-url ` | string | no | OAuth token service origin (production default: https://oauth.aliyun.com) | -| `--authorization-url ` | string | no | Explicit authorization URL; required for the first login outside pre-release | -| `--modelstudio-host ` | string | no | Model Studio POP hostname override (production default: modelstudio.cn-beijing.aliyuncs.com) | -| `--console-gateway ` | string | no | Console gateway origin override (production default: https://bailian-cs.console.aliyun.com) | -| `--bailiancontrol-host ` | string | no | Optional Bailian Control OpenAPI hostname | -| `--console-region ` | string | no | Console region (only cn-beijing; default: cn-beijing) | -| `--no-browser` | switch | no | Authorize on another device and paste the full callback URL; no local listener | - -#### Notes - -- Outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. With --no-browser, paste the complete callback URL into this login session; this is not device authorization. -- Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match. - -#### Examples - -```bash -bl auth --login aliyun --client-id --authorization-url -``` - -```bash -bl auth --login aliyun --client-id --authorization-url --no-browser -``` - -```bash -bl auth --login aliyun --client-id --authorization-url --modelstudio-host --console-gateway -``` - ### `bl auth generate-access-token` | Field | Value | @@ -89,12 +45,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] [--console-site ] [--access-key-id --access-key-secret ]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `auth login` | +| **Description** | Authenticate with API key, console browser login, OpenAPI AK/SK, or Aliyun OAuth (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 ] \| --oauth [--console-site ] [--console-region ] [--no-browser]` | #### Flags @@ -103,14 +59,27 @@ 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). Outside pre-release, creates an ordinary API key if needed; subscription plans require --api-key | -| `--no-browser` | switch | no | With --console or --open-api (setup guide), print the URL without opening a browser | +| `--no-browser` | switch | no | With --console or --open-api (setup guide), print the URL without opening a browser; with --oauth, authorize on another device and paste the full callback URL (no local listener) | | `--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 | Open the AccessKey setup guide, or save keys when --access-key-id and --access-key-secret are both set | +| `--oauth` | switch | no | Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a 30-day console session with automatic renewal | +| `--client-id ` | string | no | OAuth client ID; required for the first login outside pre-release | +| `--scope ` | string | no | OAuth scope (default: openid /internal/bailian/cli) | +| `--oauth-base-url ` | string | no | OAuth token service origin (production default: https://oauth.aliyun.com) | +| `--authorization-url ` | string | no | Explicit authorization URL; required for the first login outside pre-release | +| `--modelstudio-host ` | string | no | Model Studio POP hostname override (domestic production default: modelstudio.cn-beijing.aliyuncs.com) | +| `--console-gateway ` | string | no | Console gateway origin override (domestic production default: https://bailian-cs.console.aliyun.com) | +| `--bailiancontrol-host ` | string | no | Optional Bailian Control OpenAPI hostname | | `--access-key-id ` | string | no | Alibaba Cloud Access Key ID to store | | `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret to store | +#### Notes + +- With --oauth outside pre-release, first login requires an explicit client ID and a confirmed authorization URL. In pre-release, endpoint overrides must match the trusted endpoints, and the CLI gateway must be configured. With --no-browser, paste the complete callback URL into this login session; this is not device authorization. +- Register http://127.0.0.1:12345/oauth/callback as the IAM redirect URI. NativeApp loopback ports may vary; scheme, host and path must match. + #### Examples ```bash @@ -145,6 +114,18 @@ bl auth login --open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx bl auth login --open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx --console-site international ``` +```bash +bl auth login --oauth +``` + +```bash +bl auth login --oauth --console-site international +``` + +```bash +bl auth login --oauth --no-browser +``` + ### `bl auth logout` | Field | Value | diff --git a/skills/bailian-cli/reference/index.md b/skills/bailian-cli/reference/index.md index c06ad58b9..3a807203b 100644 --- a/skills/bailian-cli/reference/index.md +++ b/skills/bailian-cli/reference/index.md @@ -28,9 +28,8 @@ Use this index for the skill-scoped quick index and global flags. | `bl alert update` | Console | Update a model alert rule (full replacement; same fields as create) | [alert.md](alert.md) | | `bl app call` | API Key | [Deprecated] Call a Bailian application (agent or workflow) | [app.md](app.md) | | `bl app list` | Console | [Deprecated] List Bailian applications | [app.md](app.md) | -| `bl auth` | No Auth | Authenticate with Aliyun OAuth | [auth.md](auth.md) | | `bl auth generate-access-token` | AK/SK | Generate a CLI access token using OpenAPI credentials | [auth.md](auth.md) | -| `bl auth login` | No Auth | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | [auth.md](auth.md) | +| `bl auth login` | No Auth | Authenticate with API key, console browser login, OpenAPI AK/SK, or Aliyun OAuth (credentials can coexist) | [auth.md](auth.md) | | `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | [auth.md](auth.md) | | `bl auth status` | No Auth | Show current authentication state | [auth.md](auth.md) | | `bl batch cancel` | API Key | Request cancellation of a Batch task | [batch.md](batch.md) | @@ -157,7 +156,7 @@ Use this index for the skill-scoped quick index and global flags. | `agents` | `security alerts`, `security overview` | [agents.md](agents.md) | | `alert` | `create`, `delete`, `disable`, `enable`, `history`, `list`, `metrics`, `template create`, `template delete`, `template list`, `template update`, `update` | [alert.md](alert.md) | | `app` | `call`, `list` | [app.md](app.md) | -| `auth` | `(root)`, `generate-access-token`, `login`, `logout`, `status` | [auth.md](auth.md) | +| `auth` | `generate-access-token`, `login`, `logout`, `status` | [auth.md](auth.md) | | `batch` | `cancel`, `convert`, `create`, `download`, `get`, `list` | [batch.md](batch.md) | | `cmodel` | `base-models`, `delete`, `get`, `import`, `list`, `watch` | [cmodel.md](cmodel.md) | | `config` | `agent`, `list`, `set`, `show`, `ui`, `use` | [config.md](config.md) | From df3e66053902f0583f2f5255d79b2d324e448e4f Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Sat, 28 Nov 2026 21:36:18 +0800 Subject: [PATCH 06/13] test(auth): cover OAuth site/region matrix and resolve BAILIAN_PRE in E2E harness The commands E2E harness (subprocess and in-process) now resolves BAILIAN_PRE like the product entrypoint; previously pre-release cases silently ran against the online branch. Adds loginPlan quadrant coverage (domestic/international x pre/online), region override isolation, cross-site re-login rejection, profile parse compatibility and refresh-target tests. --- packages/commands/tests/auth-aliyun.test.ts | 184 ++++++++++++++++-- packages/commands/tests/e2e/auth.e2e.test.ts | 131 +++++++++++-- .../commands/tests/e2e/harness/identity.ts | 6 + packages/commands/tests/e2e/harness/main.ts | 6 +- packages/commands/tests/e2e/helpers.ts | 7 +- packages/commands/tests/e2e/topic-routes.ts | 1 - packages/core/tests/aliyun-config.test.ts | 32 +++ packages/core/tests/openapi-provider.test.ts | 41 ++++ .../core/tests/refresh-token-target.test.ts | 49 +++++ 9 files changed, 425 insertions(+), 32 deletions(-) create mode 100644 packages/core/tests/aliyun-config.test.ts create mode 100644 packages/core/tests/refresh-token-target.test.ts diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index ae9549fc1..64090e9c7 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -8,6 +8,7 @@ import { ALIYUN_CLI_SCOPE, ALIYUN_OAUTH_BASE_URL, PRE_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_ALIYUN_CLI_CLIENT_ID, PRE_MODEL_STUDIO_HOST, PRE_BAILIAN_CONTROL_HOST, BailianError, @@ -24,7 +25,8 @@ import { import { createOutputReporter } from "bailian-cli-runtime"; import { buildIsolatedCliEnv, enterIsolatedHome, type IsolatedHomeHandle } from "e2e/isolation"; import { afterEach, beforeEach, expect, test, vi, type MockInstance } from "vite-plus/test"; -import authRoot, { +import authLogin from "../src/commands/auth/login.ts"; +import { runAliyunOAuthLogin, type AliyunOAuthLoginDeps, type AliyunOAuthLoginOptions, @@ -371,21 +373,20 @@ async function finish(probe: ReturnType) { return { authUrl, callback, result }; } -test("根命令声明必填 aliyun 登录方式与双语 flags,不改变旧登录命令", () => { - expect(authRoot.auth).toBe("none"); - expect(authRoot.flags!.login).toMatchObject({ - type: "string", - required: true, - choices: ["aliyun"], +test("login 命令声明 --oauth 开关与双语 flags,站点/地域 choices 覆盖双站点", () => { + expect(authLogin.auth).toBe("none"); + expect(authLogin.flags!.oauth).toMatchObject({ type: "switch" }); + expect(authLogin.flags!.consoleRegion).toMatchObject({ + choices: ["cn-beijing", "ap-southeast-1"], + }); + expect(authLogin.flags!.consoleSite).toMatchObject({ + choices: ["domestic", "international"], }); - expect(authRoot.flags!.consoleRegion).toMatchObject({ choices: ["cn-beijing"] }); - for (const definition of Object.values(authRoot.flags!)) + for (const definition of Object.values(authLogin.flags!)) expect(definition.description).toEqual({ "en-US": expect.any(String), "zh-CN": expect.any(String), }); - expect(authRoot.flags!).not.toHaveProperty("device"); - expect(authRoot.flags!).not.toHaveProperty("tokenStdin"); }); test("完整 OAuth→STS→显式 POP→显式网关→保存链路使用 PKCE、随机 loopback 端口且不猜 Console TTL", async () => { @@ -738,8 +739,8 @@ test("产品子进程的手动登录从 stdin 读取,回调无效后遇到 EOF import.meta.resolve("tsx"), fileURLToPath(new URL("../../cli/src/main.ts", import.meta.url)), "auth", - "--login", - "aliyun", + "login", + "--oauth", "--no-browser", "--client-id", "test-client", @@ -1148,7 +1149,7 @@ test.each([ { modelstudioHost: "https://pop.example" }, { modelstudioHost: "pop.example/path" }, { bailiancontrolHost: "user@control.example" }, - { consoleRegion: "ap-southeast-1" }, + { consoleRegion: " " }, { clientId: " " }, { scope: " " }, ])("非法 URL/hostname/地域/空覆盖在监听和请求前拒绝:%j", async (options) => { @@ -1337,3 +1338,158 @@ test("dry-run 只对 HTTP loopback 端点放行,拒绝外部 HTTP", async () = expect(await invalid.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); expect(fetchMock).not.toHaveBeenCalled(); }); + +test("国内线上 dry-run plan 保持既有字段形状(回归基线)", async () => { + const probe = launch({}, { dryRun: true }); + expect(await probe.outcome).toBeUndefined(); + expect(JSON.parse(probe.stdout.join(""))).toEqual({ + action: "auth.login", + method: "aliyun", + config: "oauth-test", + no_browser: false, + plan: { + client_id: ALIYUN_CLI_CLIENT_ID, + scope: ALIYUN_CLI_SCOPE, + oauth_base_url: ENDPOINTS.oauthBaseUrl, + authorization_url: ENDPOINTS.authorizationUrl, + modelstudio_host: ENDPOINTS.modelstudioHost, + console_gateway: ENDPOINTS.consoleGateway, + bailiancontrol_host: ENDPOINTS.bailiancontrolHost, + console_region: "cn-beijing", + console_enabled: true, + openapi_enabled: true, + }, + missing: [], + }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + +test.each([false, true])( + "国际站线上 OAuth 尚未开放,live 与 dry-run 均阻断 (%s)", + async (dryRun) => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch({ consoleSite: "international" }, { dryRun }); + expect(await probe.outcome).toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringContaining("International production OAuth login is not available yet"), + }); + expect(listen).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + }, +); + +test("国际预发端点未确认时 live 阻断,零监听零请求零落盘", async () => { + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch( + { consoleSite: "international" }, + { omitEndpoints: true, preControlPlane: {} }, + ); + expect(await probe.outcome).toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringContaining("International pre-release endpoints are not confirmed yet"), + }); + expect(listen).not.toHaveBeenCalled(); + expect(probe.browser).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + +test("国际预发 dry-run 离线计入缺失端点,给出内置 clientId 与 ap-southeast-1", async () => { + const probe = launch( + { consoleSite: "international" }, + { dryRun: true, omitEndpoints: true, preControlPlane: {} }, + ); + expect(await probe.outcome).toBeUndefined(); + const data = JSON.parse(probe.stdout.join("")); + expect(data.environment).toBe("pre"); + expect(data.missing).toEqual(["--authorization-url", "BAILIAN_PRE_CONSOLE_GATEWAY"]); + expect(data.plan).toMatchObject({ + client_id: PRE_INTL_ALIYUN_CLI_CLIENT_ID, + scope: ALIYUN_CLI_SCOPE, + console_region: "ap-southeast-1", + console_site: "international", + console_enabled: true, + openapi_enabled: true, + }); + expect(data.plan.authorization_url).toBeUndefined(); + expect(data.plan.oauth_base_url).toBeUndefined(); + expect(data.plan.modelstudio_host).toBeUndefined(); + expect(data.plan.console_gateway).toBeUndefined(); + expect(probe.describe).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + +test("dry-run 地域缺省按 site 推导,显式覆盖切换默认 POP/网关但不改 OAuth 端点", async () => { + const domestic = launch({}, { dryRun: true, omitEndpoints: true }); + expect(await domestic.outcome).toBeUndefined(); + const domesticPlan = JSON.parse(domestic.stdout.join("")).plan; + expect(domesticPlan.console_region).toBe("cn-beijing"); + expect(domesticPlan.modelstudio_host).toBe(DEFAULT_ENDPOINTS.modelstudioHost); + expect(domesticPlan.console_gateway).toBe(DEFAULT_ENDPOINTS.consoleGateway); + + const overridden = launch( + { consoleRegion: "ap-southeast-1" }, + { dryRun: true, omitEndpoints: true }, + ); + expect(await overridden.outcome).toBeUndefined(); + const overriddenPlan = JSON.parse(overridden.stdout.join("")).plan; + expect(overriddenPlan.console_region).toBe("ap-southeast-1"); + expect(overriddenPlan.modelstudio_host).toBe("modelstudio.ap-southeast-1.aliyuncs.com"); + expect(overriddenPlan.console_gateway).toBe("https://modelstudio-cs.console.aliyun.com"); + expect(overriddenPlan.oauth_base_url).toBe(domesticPlan.oauth_base_url); + expect(overriddenPlan).not.toHaveProperty("console_site"); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +test("线上国内显式地域覆盖落盘与网关路由,OAuth 换票端点不随 region 变化", async () => { + const probe = launch({ consoleRegion: "ap-southeast-1" }); + await finish(probe); + expect(requests[0]!.url.origin).toBe(ENDPOINTS.oauthBaseUrl); + expect(requests[1]!.url.origin).toBe(ENDPOINTS.oauthBaseUrl); + expect(requests[2]!.url.host).toBe(ENDPOINTS.modelstudioHost); + const gateway = requests[3]!; + expect(gateway.url.origin).toBe(ENDPOINTS.consoleGateway); + expect(gateway.url.searchParams.get("action")).toBe("IntlBroadScopeAspnGateway"); + expect(new URLSearchParams(stringBody(gateway.init.body)).get("region")).toBe("ap-southeast-1"); + const [profile, session] = probe.save.mock.calls[0]!; + expect(profile.console_region).toBe("ap-southeast-1"); + expect(profile).not.toHaveProperty("console_site"); + expect(session.consoleTokens).toEqual({ + [consoleCredentialKey({ + region: "ap-southeast-1", + site: "domestic", + gateway: ENDPOINTS.consoleGateway, + })]: { token: SECRETS.cliAccessToken }, + }); + assertNoSecrets(probe); +}); + +test("跨站点重登不复用旧站点 Profile,按全新登录要求显式端点", async () => { + const previous: AliyunOAuthProfile = { + client_id: "intl-stored-client", + scope: "openid", + authorization_url: "https://intl-authorize.example/authorize", + oauth_base_url: "https://intl-oauth.example", + modelstudio_host: "intl-pop.example", + console_gateway: "https://intl-console.example", + console_region: "ap-southeast-1", + console_site: "international", + session_ref: "test-session-reference", + console_enabled: true, + openapi_enabled: true, + }; + const listen = vi.spyOn(http.Server.prototype, "listen"); + const probe = launch( + { consoleSite: "domestic", clientId: undefined, authorizationUrl: undefined }, + { omitEndpoints: true, previous }, + ); + expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); + expect(probe.describe).toHaveBeenCalledTimes(1); + expect(listen).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index e634850c0..c349a33ba 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -61,25 +61,25 @@ afterAll(async () => { }); describe("e2e: auth", () => { - test("auth 父命令暴露 aliyun 登录且保留既有子命令", async () => { + test("auth 分组帮助保留既有子命令且不再暴露旧 aliyun 根入口", async () => { const result = await runCommandHelp(AUTH_ROUTES, ["auth", "--help"]); expect(result.exitCode, result.stderr).toBe(0); - for (const flag of [ - "--login", - "--authorization-url", - "--modelstudio-host", - "--console-gateway", - ]) - expect(result.stderr).toContain(flag); for (const command of ["auth login", "auth status", "auth logout"]) expect(result.stderr).toContain(command); + expect(result.stderr).not.toContain("--login"); + }); + + test("旧入口 auth --login aliyun 已移除,按用法错误退出", async () => { + const result = await runCommandE2e(AUTH_ROUTES, ["auth", "--login", "aliyun"]); + expect(result.exitCode).toBe(2); + expect(result.stdout).toBe(""); }); test("aliyun dry-run 仅返回配置计划与缺少的端点", async () => { const result = await runCommandInProcess(AUTH_ROUTES, [ "auth", - "--login", - "aliyun", + "login", + "--oauth", "--dry-run", "--output", "json", @@ -106,8 +106,8 @@ describe("e2e: auth", () => { test("aliyun 首次登录未给授权地址时在授权前失败", async () => { const result = await runCommandInProcess(AUTH_ROUTES, [ "auth", - "--login", - "aliyun", + "login", + "--oauth", "--output", "json", ]); @@ -144,6 +144,111 @@ describe("e2e: auth", () => { expect(stderr).toMatch(/Choose exactly one login mode/); }); + test.each([["--api-key", "sk-e2e-placeholder"], ["--console"], ["--open-api"]])( + "auth login --oauth 与其它模式互斥 (%s)", + async (...extra) => { + const { stderr, exitCode } = await runCommandE2e(AUTH_ROUTES, [ + "auth", + "login", + "--oauth", + ...extra, + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/Choose exactly one login mode/); + }, + ); + + test.each([ + ["--client-id", "test-client"], + ["--scope", "openid"], + ["--oauth-base-url", "https://oauth.example"], + ["--authorization-url", "https://signin.example/oauth2/v1/auth"], + ["--modelstudio-host", "modelstudio.example"], + ["--console-gateway", "https://console.example"], + ["--bailiancontrol-host", "control.example"], + ])("OAuth 专属参数脱离 --oauth 报用法错误 (%s)", async (...extra) => { + const { stderr, exitCode } = await runCommandE2e(AUTH_ROUTES, ["auth", "login", ...extra]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/only with --oauth/); + }); + + test("auth login --oauth 允许 --console-region 与 --console-site,dry-run 按显式地域落计划", async () => { + const result = await runCommandInProcess(AUTH_ROUTES, [ + "auth", + "login", + "--oauth", + "--console-region", + "ap-southeast-1", + "--dry-run", + "--output", + "json", + ]); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + plan: { console_region: string; modelstudio_host: string; console_gateway: string }; + }>(result.stdout); + expect(data.plan.console_region).toBe("ap-southeast-1"); + expect(data.plan.modelstudio_host).toBe("modelstudio.ap-southeast-1.aliyuncs.com"); + expect(data.plan.console_gateway).toBe("https://modelstudio-cs.console.aliyun.com"); + }); + + test("国际站线上 OAuth 未开放:--oauth --console-site international 阻断", async () => { + const result = await runCommandInProcess( + AUTH_ROUTES, + [ + "auth", + "login", + "--oauth", + "--console-site", + "international", + "--dry-run", + "--output", + "json", + ], + { BAILIAN_PRE: "0" }, + ); + expect(result.exitCode).toBe(2); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("International production OAuth login is not available yet"); + expect(result.stderr).toContain("国际站线上 OAuth 登录尚未开放"); + }); + + test("国际预发端点未确认:live 阻断,dry-run 离线列出缺失端点", async () => { + const live = await runCommandInProcess( + AUTH_ROUTES, + ["auth", "login", "--oauth", "--console-site", "international", "--output", "json"], + { BAILIAN_PRE: "1" }, + ); + expect(live.exitCode).toBe(2); + expect(live.stderr).toContain("International pre-release endpoints are not confirmed yet"); + + const dryRun = await runCommandInProcess( + AUTH_ROUTES, + [ + "auth", + "login", + "--oauth", + "--console-site", + "international", + "--dry-run", + "--output", + "json", + ], + { BAILIAN_PRE: "1" }, + ); + expect(dryRun.exitCode, dryRun.stderr).toBe(0); + const data = parseStdoutJson<{ + environment: string; + plan: { client_id: string; console_region: string; console_site: string }; + missing: string[]; + }>(dryRun.stdout); + expect(data.environment).toBe("pre"); + expect(data.plan.client_id).toBe("4102369295402391842"); + expect(data.plan.console_region).toBe("ap-southeast-1"); + expect(data.plan.console_site).toBe("international"); + expect(data.missing).toEqual(["--authorization-url", "BAILIAN_PRE_CONSOLE_GATEWAY"]); + }); + test("auth login 模式专属参数不能脱离对应模式", async () => { const openApiFlagOnly = await runCommandE2e(AUTH_ROUTES, [ "auth", @@ -174,7 +279,7 @@ describe("e2e: auth", () => { ]); expect(consoleSiteWithoutConsole.exitCode).toBe(2); expect(consoleSiteWithoutConsole.stderr).toMatch( - /Use --console-site with --console or --open-api/, + /Use --console-site with --console, --open-api, or --oauth/, ); }); diff --git a/packages/commands/tests/e2e/harness/identity.ts b/packages/commands/tests/e2e/harness/identity.ts index 292a183a9..a342e3382 100644 --- a/packages/commands/tests/e2e/harness/identity.ts +++ b/packages/commands/tests/e2e/harness/identity.ts @@ -1,3 +1,4 @@ +import { resolvePreControlPlane } from "bailian-cli-core"; import pkg from "../../../package.json" with { type: "json" }; /** @@ -11,3 +12,8 @@ export const E2E_HARNESS_IDENTITY = { clientName: "commands-e2e", npmPackage: "bailian-cli-commands-e2e-harness", } as const; + +/** 与产品入口 main.ts 对齐:harness 也解析 BAILIAN_PRE,否则预发用例在 e2e 层失真。 */ +export const E2E_HARNESS_CLI_OPTIONS = { + preControlPlane: () => resolvePreControlPlane(process.env), +} as const; diff --git a/packages/commands/tests/e2e/harness/main.ts b/packages/commands/tests/e2e/harness/main.ts index 67d885ae8..a26714218 100644 --- a/packages/commands/tests/e2e/harness/main.ts +++ b/packages/commands/tests/e2e/harness/main.ts @@ -1,5 +1,5 @@ import { createCli } from "bailian-cli-runtime"; -import { E2E_HARNESS_IDENTITY } from "./identity.ts"; +import { E2E_HARNESS_CLI_OPTIONS, E2E_HARNESS_IDENTITY } from "./identity.ts"; import { loadRouteCommands } from "./routes.ts"; import { withHarnessUpdateFixture } from "./update-fixture.ts"; @@ -14,7 +14,9 @@ async function main(): Promise { const spec = JSON.parse(raw) as RouteSpec[]; const routes = Object.fromEntries(spec.map(({ path, export: exportName }) => [path, exportName])); const commands = await loadRouteCommands(routes); - await withHarnessUpdateFixture(() => createCli(commands, E2E_HARNESS_IDENTITY).run()); + await withHarnessUpdateFixture(() => + createCli(commands, { ...E2E_HARNESS_IDENTITY, ...E2E_HARNESS_CLI_OPTIONS }).run(), + ); } void main(); diff --git a/packages/commands/tests/e2e/helpers.ts b/packages/commands/tests/e2e/helpers.ts index 685348c4c..cc994a532 100644 --- a/packages/commands/tests/e2e/helpers.ts +++ b/packages/commands/tests/e2e/helpers.ts @@ -14,7 +14,7 @@ import { buildIsolatedCliEnv } from "e2e/isolation"; import { runInProcess } from "e2e/in-process"; import { CommandRegistry, createCli, resolve } from "bailian-cli-runtime"; import { loadRouteCommands } from "./harness/routes.ts"; -import { E2E_HARNESS_IDENTITY } from "./harness/identity.ts"; +import { E2E_HARNESS_CLI_OPTIONS, E2E_HARNESS_IDENTITY } from "./harness/identity.ts"; import { withHarnessUpdateFixture } from "./harness/update-fixture.ts"; import type { E2eRouteExports } from "./topic-routes.ts"; @@ -157,7 +157,10 @@ export async function runCommandInProcess( try { const commands = await loadRouteCommands(routes); return await runInProcess( - () => withHarnessUpdateFixture(() => createCli(commands, E2E_HARNESS_IDENTITY).run(args)), + () => + withHarnessUpdateFixture(() => + createCli(commands, { ...E2E_HARNESS_IDENTITY, ...E2E_HARNESS_CLI_OPTIONS }).run(args), + ), args, { cwd: options.cwd ?? commandsPackageRoot, env: isolated.env, entrypoint: harnessMainTs }, ); diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index d45c7c937..bc7a59236 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -5,7 +5,6 @@ export type E2eRouteExports = Record; export const AUTH_ROUTES: E2eRouteExports = { - auth: "authRoot", "auth login": "authLogin", "auth status": "authStatus", "auth logout": "authLogout", diff --git a/packages/core/tests/aliyun-config.test.ts b/packages/core/tests/aliyun-config.test.ts new file mode 100644 index 000000000..fc559235e --- /dev/null +++ b/packages/core/tests/aliyun-config.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from "vite-plus/test"; +import { parseAliyunOAuthProfile, profileSite } from "../src/auth/aliyun-config.ts"; +import { UsageError } from "../src/errors/base.ts"; + +const PROFILE = { + client_id: "fixture-client", + scope: "openid /internal/bailian/cli", + authorization_url: "https://authorize.example.test/authorize", + oauth_base_url: "https://oauth.example.test", + modelstudio_host: "modelstudio.example.test", + console_gateway: "https://console.example.test", + console_region: "cn-beijing", + session_ref: "11111111-1111-4111-8111-111111111111", + console_enabled: true, + openapi_enabled: true, +}; + +test("旧 Profile 无 console_site 时解析兼容且缺省国内站", () => { + const parsed = parseAliyunOAuthProfile(PROFILE); + expect(parsed.console_site).toBeUndefined(); + expect(profileSite(parsed)).toBe("domestic"); +}); + +test.each(["domestic", "international"] as const)("console_site=%s 原样保留", (site) => { + const parsed = parseAliyunOAuthProfile({ ...PROFILE, console_site: site }); + expect(parsed.console_site).toBe(site); + expect(profileSite(parsed)).toBe(site); +}); + +test.each(["", "intl", 1, null])("非法 console_site 拒绝:%j", (site) => { + expect(() => parseAliyunOAuthProfile({ ...PROFILE, console_site: site })).toThrow(UsageError); +}); diff --git a/packages/core/tests/openapi-provider.test.ts b/packages/core/tests/openapi-provider.test.ts index f157368ea..6ab289ad9 100644 --- a/packages/core/tests/openapi-provider.test.ts +++ b/packages/core/tests/openapi-provider.test.ts @@ -838,6 +838,47 @@ describe("Console cache and endpoint isolation", () => { expect(transport).not.toHaveBeenCalled(); }); + test("international Profile 匹配国际 Console 目标,站点进入配置指纹", async () => { + const intlProfile = profile({ + console_site: "international", + console_region: "ap-southeast-1", + }); + const instance = await setup({ file: { aliyun_oauth: intlProfile } }); + const target = { region: "ap-southeast-1", site: "international" as const }; + expect(instance.provider.resolveConsoleTarget(target)).toEqual({ + ...target, + gateway: intlProfile.console_gateway, + }); + expect(() => instance.provider.resolveConsoleTarget(TARGET)).toThrow(UsageError); + expect(oauthConfigurationFingerprint(intlProfile)).not.toBe( + oauthConfigurationFingerprint(profile()), + ); + }); + + test("console_site 变更后旧指纹会话失效,需要重新登录", async () => { + const instance = await setup(); + await instance.provider.saveConsoleCredential({ + ...TARGET, + token: "fixture-console-token", + method: "aliyun-oauth", + sessionRef: REFERENCE, + configurationFingerprint: oauthConfigurationFingerprint(profile()), + source: "config", + }); + await writeConfigFile({ + aliyun_oauth: profile({ + console_site: "international", + console_region: "ap-southeast-1", + }), + }); + await expect( + instance.provider.getConsoleCredential({ + region: "ap-southeast-1", + site: "international", + }), + ).rejects.toBeInstanceOf(CredentialError); + }); + test("cache keys distinguish gateway, region, site and switchAgent including zero", () => { const targets = [ TARGET, diff --git a/packages/core/tests/refresh-token-target.test.ts b/packages/core/tests/refresh-token-target.test.ts new file mode 100644 index 000000000..aa04c0a1f --- /dev/null +++ b/packages/core/tests/refresh-token-target.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from "vite-plus/test"; +import { resolveCLIAccessTokenTarget } from "../src/auth/refresh-token.ts"; +import { UsageError } from "../src/errors/base.ts"; + +const BASE_URL = "https://dashscope.aliyuncs.com"; + +test("预发缺省按国内站推导 cn-beijing/domestic", () => { + expect(resolveCLIAccessTokenTarget({ preControlPlane: {} }, BASE_URL)).toEqual({ + region: "cn-beijing", + site: "domestic", + }); +}); + +test("预发显式国内地域放行,跨地域组合拒绝", () => { + expect( + resolveCLIAccessTokenTarget({ consoleRegion: "cn-beijing", preControlPlane: {} }, BASE_URL), + ).toMatchObject({ region: "cn-beijing", site: "domestic" }); + expect(() => + resolveCLIAccessTokenTarget({ consoleRegion: "ap-southeast-1", preControlPlane: {} }, BASE_URL), + ).toThrow(UsageError); +}); + +test("预发国际站端点未确认时阻断,错误地域组合优先拒绝", () => { + expect(() => + resolveCLIAccessTokenTarget({ consoleSite: "international", preControlPlane: {} }, BASE_URL), + ).toThrow("International pre-release endpoints are not confirmed yet"); + expect(() => + resolveCLIAccessTokenTarget( + { consoleSite: "international", consoleRegion: "cn-beijing", preControlPlane: {} }, + BASE_URL, + ), + ).toThrow("pre-release control plane supports"); +}); + +test("线上地域与站点独立,显式配置原样返回", () => { + expect( + resolveCLIAccessTokenTarget( + { consoleRegion: "ap-southeast-1", consoleSite: "international" }, + BASE_URL, + ), + ).toEqual({ region: "ap-southeast-1", site: "international" }); +}); + +test("线上缺省地域从已知模型域名推导", () => { + expect(resolveCLIAccessTokenTarget({}, "https://dashscope-intl.aliyuncs.com").region).toBe( + "ap-southeast-1", + ); + expect(resolveCLIAccessTokenTarget({}, BASE_URL).region).toBe("cn-beijing"); +}); From 4d13dcfec888d990507fe276445776f8f8289962 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Sat, 28 Nov 2026 21:36:33 +0800 Subject: [PATCH 07/13] docs(auth): document auth login --oauth and international pre-release status Update README copies, the auth-change agent guide and regenerated skill references for the new OAuth entry, site/region semantics, the confirmed international pre-release application and the pending endpoint group. --- README.md | 16 +++++++++------- README.zh.md | 16 +++++++++------- docs/agents/auth-change.md | 7 ++++--- packages/cli/README.md | 16 +++++++++------- packages/cli/README.zh.md | 16 +++++++++------- 5 files changed, 40 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 6db5ae764..da22fc67c 100644 --- a/README.md +++ b/README.md @@ -192,32 +192,34 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ### Aliyun OAuth -`bl auth --login aliyun` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. For a first online login, provide the confirmed production application ID and authorization URL: +`bl auth login --oauth` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. `--console-site ` selects the site (default `domestic`). For a first domestic online login, provide the confirmed production application ID and authorization URL: ```bash -bl auth --login aliyun --config aliyun \ +bl auth login --oauth --config aliyun \ --client-id \ --authorization-url ``` Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. -Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. +Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. `--console-region ` only sets the `console_region` saved to config.json and the Console routing; the OAuth authorization/token/exchange endpoints follow the site alone. It defaults to `cn-beijing` for domestic and `ap-southeast-1` for international. -For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth --login aliyun --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. +International site: `bl auth login --oauth --console-site international`. The international pre-release IAM application is approved and its client ID is built in, but the remaining pre-release endpoints are not confirmed yet, so login stays blocked until they are filled in; `--dry-run` lists the missing items offline. International production login is not available yet because the production application has not been approved. + +For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth login --oauth --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. ```bash -bl auth --login aliyun --config aliyun --no-browser +bl auth login --oauth --config aliyun --no-browser ``` The example reuses an already configured OAuth Profile; first online login still requires `--client-id` and `--authorization-url`. #### Domestic pre-release control plane -Set `BAILIAN_PRE=1` (or `true`) to select the domestic `cn-beijing` control plane. Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. +Set `BAILIAN_PRE=1` (or `true`) to select the pre-release control plane: domestic `cn-beijing`, or international `ap-southeast-1` with `--console-site international` (blocked until the international endpoint group is confirmed). Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. ```bash -BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth login --oauth --dry-run BAILIAN_PRE=1 bl auth status ``` diff --git a/README.zh.md b/README.zh.md index 4f34b9a2c..115d8e0b9 100644 --- a/README.zh.md +++ b/README.zh.md @@ -191,32 +191,34 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ### 阿里云 OAuth -`bl auth --login aliyun` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。首次在线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: +`bl auth login --oauth` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。`--console-site ` 选择站点(缺省 `domestic`)。首次在国内线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: ```bash -bl auth --login aliyun --config aliyun \ +bl auth login --oauth --config aliyun \ --client-id <正式应用ID> \ --authorization-url <已确认的授权地址> ``` IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 -线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 +线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。`--console-region ` 只决定写入 config.json 的 `console_region` 与控制台路由;OAuth 授权/换票端点仅由站点决定。缺省按站点推导:国内 `cn-beijing`,国际 `ap-southeast-1`。 -SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth --login aliyun --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 +国际站:`bl auth login --oauth --console-site international`。国际预发 IAM 应用已获批,client ID 已内置;其余预发端点尚未确认,确认填入前登录保持阻断,`--dry-run` 可离线列出缺失项。国际站线上应用未申请,线上登录尚未开放。 + +SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth login --oauth --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 ```bash -bl auth --login aliyun --config aliyun --no-browser +bl auth login --oauth --config aliyun --no-browser ``` 示例复用已配置的 OAuth Profile;线上首次登录仍须提供 `--client-id` 和 `--authorization-url`。 #### 国内预发控制面 -用 `BAILIAN_PRE=1`(也接受 `true`)切换国内 `cn-beijing` 控制面;未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 +用 `BAILIAN_PRE=1`(也接受 `true`)切换预发控制面:国内 `cn-beijing`,或配合 `--console-site international` 使用国际 `ap-southeast-1`(国际端点组确认前保持阻断);未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 ```bash -BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth login --oauth --dry-run BAILIAN_PRE=1 bl auth status ``` diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index a3f7c1a97..660d97aa5 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -78,15 +78,15 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx ### 阿里云 OAuth 登录与续期 -- `bl auth --login aliyun` 是可执行的 `auth` 父命令,保留既有 `auth login/status/logout` 子命令;不在 runtime 改写 argv。 +- OAuth 入口是 `bl auth login --oauth [--console-site ] [--console-region ]`,与 `--api-key` / `--console` / `--open-api` 并列为第四种登录模式;7 个 OAuth 专属 flag(`--client-id` / `--scope` / `--oauth-base-url` / `--authorization-url` / `--modelstudio-host` / `--console-gateway` / `--bailiancontrol-host`)定义在 `auth/aliyun-flags.ts`,脱离 `--oauth` 报用法错误。旧 `bl auth --login aliyun` 根入口已移除(仅 beta 存在过,无 stable 兼容负担);`aliyun.ts` 只保留 `runAliyunOAuthLogin` 与 loginPlan,不再是 defineCommand。 - 默认 OAuth 回调仅监听 `127.0.0.1` 随机端口的 `/oauth/callback` 路径,授权请求与换票使用同一 `redirect_uri`。IAM 登记 `http://127.0.0.1:12345/oauth/callback`;NativeApp 忽略回环端口,但协议、主机和路径必须一致,不保留根路径兼容。 - OAuth 的 `--no-browser` 显式选择跨设备手动授权:固定使用已登记的 `http://127.0.0.1:12345/oauth/callback`,不启服务器,在原进程粘贴完整回调 URL;校验地址、唯一且匹配的 state、唯一非空 code,拒绝 userinfo、fragment、非法查询编码、解码后包含控制字符的查询与其它登录会话。有可关闭回显的 TTY 时隐藏输入,非 TTY 提示上游终端可能回显;不保存输入历史。错误输入可重试但不重新生成 state/PKCE;有效 state 的授权拒绝、EOF、超长输入、Ctrl+C、Ctrl+Z 或超时结束登录。与默认流共用换票、落盘及取消处理,不自动降级、不提供设备码流程,不改变 `auth login --console --no-browser` 的本机回调语义。 -- 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile;端点维持显式参数 > Profile > 默认地址。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和已确认的国内端点,不读线上控制面凭据、不隐式回退、不改 hosts/代理。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 +- 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile(仅同 site 复用);端点维持显式参数 > Profile > 默认地址。`--console-region` 只决定写入 config.json 的 `console_region` 与控制台路由(REGION_GATEWAYS 四组合齐全),缺省按 site 推导(domestic→cn-beijing,international→ap-southeast-1),显式值自由覆盖、不做 site×region 配对拒绝;OAuth 前三跳(signin/token/exchange)端点仅由 site 决定。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和按 site 分组的端点常量(`control-plane.ts` 的 `PRE_DOMESTIC_GROUP` / `PRE_INTL_GROUP`),不读线上控制面凭据、不隐式回退、不改 hosts/代理。国际预发 IAM 应用已获批(client ID 内置 `PRE_INTL_ALIYUN_CLI_CLIENT_ID`),其余端点占位 undefined:未确认时 live 抛 `unconfirmedIntlPreError()` 双语阻断、dry-run 计入 missing,零网络零写盘;**禁止猜测域名**,确认后填常量组即解锁(独立 commit)。国际线上应用未申请,`international × online` 硬阻断(dry-run 同样报错)。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 - `aliyun_oauth` 仅保存端点、client_id/scope、会话引用、域激活状态及到期元数据;OAuth AT 不覆盖旧的 Console `access_token`。凭据存于配置目录下独立的 `oauth/.json` 明文文件,绑定会话引用,不写入主配置。Unix 校验目录 `0700` 和文件 `0600` 及所有者,Windows 校验私有 ACL;拒绝非普通文件及链接,使用同目录唯一临时文件、fsync 和原子替换。旧加密会话不迁移,需要重新登录。 - 同一个异步 OpenAPI provider 负责 OAuth AT/RT→STS,Console 换票与 OpenAPI 签名前复用。优先级保持 flag > 百炼 env > 所选 file(静态或 OAuth)> 阿里云 env;临时来源不落盘。`describe/stored` 只读元数据,不读取凭据文件;静态 dry-run 不调用 OAuth,框架更新/遥测仍遵循原设置。 - `/v1/exchange` 接受完整的 PascalCase 或 camelCase STS 字段,不跨两套字段拼接。两种格式均校验非空字符串凭据及未来到期时间,不输出原始响应体。 - RT 刷新开始前保存 pending 状态;新 RT 必须安全持久化后才能继续 STS/业务请求。刷新结果不确定时不重放旧 RT;没有返回新 RT 时保留旧值。会话锁跨进程协调,配置写入使用文件锁、唯一临时文件与原子替换。 -- 会话文件绑定端点/client/scope 指纹,公开元数据被改动时须重新登录,不能把旧 RT 发往新端点;Console 缓存按 gateway/region/site/switchAgent 隔离。Console token 仍保持原业务请求成功后才保存的规则。 +- 会话文件绑定端点/client/scope/**site** 指纹(`oauthConfigurationFingerprint` 含 `console_site ?? "domestic"`),公开元数据被改动时须重新登录,不能把旧 RT 发往新端点;存量 beta 会话因指纹加入 site 一次性失效需重登(CHANGELOG 已注明)。Console 缓存按 gateway/region/site/switchAgent 隔离。Console token 仍保持原业务请求成功后才保存的规则。 - `workspace init` 是 OpenAPI 与 Console 混合命令,以 `auth: "openapi"` 校验主凭据,两类调用均经过同一个 Client;纯 Console Gateway 命令仍声明 `auth: "console"`。`auth generate-access-token` 也复用所选 OpenAPI 凭据,不再要求手工重复输入已登录的凭据。 - 完整退出或 `--aliyun` 撤销 RT 并删除安全缓存;部分 `--console`/`--open-api` 仅停用对应域。删除有 OAuth 会话的 Profile 前必须先退出 OAuth,避免遗留无法撤销的安全缓存。重新登录替换本地引用,不把本地替换描述为服务端旧授权已撤销。 @@ -189,6 +189,7 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx ### E. 测试 - [ ] `packages/commands/tests/e2e/auth.e2e.test.ts` 增加新方式的 happy / failure 路径;浏览器回调契约在 `packages/commands/tests/login-console.test.ts` 覆盖 +- [ ] e2e harness 与产品入口对齐解析 `BAILIAN_PRE`(`harness/identity.ts` 的 `E2E_HARNESS_CLI_OPTIONS`,subprocess 与 in-process 两条路径共用);预发用例不得只在单测注入 `deps.settings.preControlPlane` 而绕过 harness 验证 - [ ] mask token 的输出格式不变(避免泄漏) - [ ] 如调整 resolver 优先级,补 core/runtime 单测覆盖对应凭证链;AK/SK 为 flag > 百炼 env > file > 阿里云 env,并验证不跨来源拼接 diff --git a/packages/cli/README.md b/packages/cli/README.md index 6db5ae764..da22fc67c 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -192,32 +192,34 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ### Aliyun OAuth -`bl auth --login aliyun` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. For a first online login, provide the confirmed production application ID and authorization URL: +`bl auth login --oauth` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. `--console-site ` selects the site (default `domestic`). For a first domestic online login, provide the confirmed production application ID and authorization URL: ```bash -bl auth --login aliyun --config aliyun \ +bl auth login --oauth --config aliyun \ --client-id \ --authorization-url ``` Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. -Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. +Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. `--console-region ` only sets the `console_region` saved to config.json and the Console routing; the OAuth authorization/token/exchange endpoints follow the site alone. It defaults to `cn-beijing` for domestic and `ap-southeast-1` for international. -For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth --login aliyun --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. +International site: `bl auth login --oauth --console-site international`. The international pre-release IAM application is approved and its client ID is built in, but the remaining pre-release endpoints are not confirmed yet, so login stays blocked until they are filled in; `--dry-run` lists the missing items offline. International production login is not available yet because the production application has not been approved. + +For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth login --oauth --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. ```bash -bl auth --login aliyun --config aliyun --no-browser +bl auth login --oauth --config aliyun --no-browser ``` The example reuses an already configured OAuth Profile; first online login still requires `--client-id` and `--authorization-url`. #### Domestic pre-release control plane -Set `BAILIAN_PRE=1` (or `true`) to select the domestic `cn-beijing` control plane. Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. +Set `BAILIAN_PRE=1` (or `true`) to select the pre-release control plane: domestic `cn-beijing`, or international `ap-southeast-1` with `--console-site international` (blocked until the international endpoint group is confirmed). Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. ```bash -BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth login --oauth --dry-run BAILIAN_PRE=1 bl auth status ``` diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index 4f34b9a2c..115d8e0b9 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -191,32 +191,34 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ### 阿里云 OAuth -`bl auth --login aliyun` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。首次在线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: +`bl auth login --oauth` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。`--console-site ` 选择站点(缺省 `domestic`)。首次在国内线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: ```bash -bl auth --login aliyun --config aliyun \ +bl auth login --oauth --config aliyun \ --client-id <正式应用ID> \ --authorization-url <已确认的授权地址> ``` IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 -线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。 +线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。`--console-region ` 只决定写入 config.json 的 `console_region` 与控制台路由;OAuth 授权/换票端点仅由站点决定。缺省按站点推导:国内 `cn-beijing`,国际 `ap-southeast-1`。 -SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth --login aliyun --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 +国际站:`bl auth login --oauth --console-site international`。国际预发 IAM 应用已获批,client ID 已内置;其余预发端点尚未确认,确认填入前登录保持阻断,`--dry-run` 可离线列出缺失项。国际站线上应用未申请,线上登录尚未开放。 + +SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth login --oauth --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 ```bash -bl auth --login aliyun --config aliyun --no-browser +bl auth login --oauth --config aliyun --no-browser ``` 示例复用已配置的 OAuth Profile;线上首次登录仍须提供 `--client-id` 和 `--authorization-url`。 #### 国内预发控制面 -用 `BAILIAN_PRE=1`(也接受 `true`)切换国内 `cn-beijing` 控制面;未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 +用 `BAILIAN_PRE=1`(也接受 `true`)切换预发控制面:国内 `cn-beijing`,或配合 `--console-site international` 使用国际 `ap-southeast-1`(国际端点组确认前保持阻断);未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 ```bash -BAILIAN_PRE=1 bl auth --login aliyun --dry-run +BAILIAN_PRE=1 bl auth login --oauth --dry-run BAILIAN_PRE=1 bl auth status ``` From 6934e384842acfae7c5a23563140ac3ee7d731f8 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Sat, 28 Nov 2026 21:57:34 +0800 Subject: [PATCH 08/13] feat(auth): fill confirmed international pre-release OAuth and console endpoints signin/oauth come from the IMS open docs; console origin/gateway match inner-console-call pre.singapore. The two OpenAPI hosts stay unconfirmed, so live international pre-release login remains gated. --- packages/commands/tests/auth-aliyun.test.ts | 8 +++++--- packages/commands/tests/e2e/auth.e2e.test.ts | 12 ++++++++++-- packages/core/src/config/control-plane.ts | 18 ++++++++++++------ 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index 64090e9c7..fbabeed24 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -8,7 +8,9 @@ import { ALIYUN_CLI_SCOPE, ALIYUN_OAUTH_BASE_URL, PRE_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_ALIYUN_AUTHORIZATION_URL, PRE_INTL_ALIYUN_CLI_CLIENT_ID, + PRE_INTL_ALIYUN_OAUTH_BASE_URL, PRE_MODEL_STUDIO_HOST, PRE_BAILIAN_CONTROL_HOST, BailianError, @@ -1405,7 +1407,7 @@ test("国际预发 dry-run 离线计入缺失端点,给出内置 clientId 与 expect(await probe.outcome).toBeUndefined(); const data = JSON.parse(probe.stdout.join("")); expect(data.environment).toBe("pre"); - expect(data.missing).toEqual(["--authorization-url", "BAILIAN_PRE_CONSOLE_GATEWAY"]); + expect(data.missing).toEqual(["BAILIAN_PRE_CONSOLE_GATEWAY"]); expect(data.plan).toMatchObject({ client_id: PRE_INTL_ALIYUN_CLI_CLIENT_ID, scope: ALIYUN_CLI_SCOPE, @@ -1414,8 +1416,8 @@ test("国际预发 dry-run 离线计入缺失端点,给出内置 clientId 与 console_enabled: true, openapi_enabled: true, }); - expect(data.plan.authorization_url).toBeUndefined(); - expect(data.plan.oauth_base_url).toBeUndefined(); + expect(data.plan.authorization_url).toBe(PRE_INTL_ALIYUN_AUTHORIZATION_URL); + expect(data.plan.oauth_base_url).toBe(PRE_INTL_ALIYUN_OAUTH_BASE_URL); expect(data.plan.modelstudio_host).toBeUndefined(); expect(data.plan.console_gateway).toBeUndefined(); expect(probe.describe).not.toHaveBeenCalled(); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index c349a33ba..8d67927b6 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -239,14 +239,22 @@ describe("e2e: auth", () => { expect(dryRun.exitCode, dryRun.stderr).toBe(0); const data = parseStdoutJson<{ environment: string; - plan: { client_id: string; console_region: string; console_site: string }; + plan: { + client_id: string; + console_region: string; + console_site: string; + authorization_url: string; + oauth_base_url: string; + }; missing: string[]; }>(dryRun.stdout); expect(data.environment).toBe("pre"); expect(data.plan.client_id).toBe("4102369295402391842"); expect(data.plan.console_region).toBe("ap-southeast-1"); expect(data.plan.console_site).toBe("international"); - expect(data.missing).toEqual(["--authorization-url", "BAILIAN_PRE_CONSOLE_GATEWAY"]); + expect(data.plan.authorization_url).toBe("https://signin.alibabacloud.com/oauth2/v1/auth"); + expect(data.plan.oauth_base_url).toBe("https://pre-ims-oauth-intl-share.aliyun-inc.com"); + expect(data.missing).toEqual(["BAILIAN_PRE_CONSOLE_GATEWAY"]); }); test("auth login 模式专属参数不能脱离对应模式", async () => { diff --git a/packages/core/src/config/control-plane.ts b/packages/core/src/config/control-plane.ts index 6a5adc460..ca1f03c4c 100644 --- a/packages/core/src/config/control-plane.ts +++ b/packages/core/src/config/control-plane.ts @@ -10,14 +10,20 @@ export const PRE_BAILIAN_CONTROL_HOST = "bailiancontrol-pre.aliyuncs.com"; const PRE_CONSOLE_ORIGIN = "https://pre-bailian.console.aliyun.com"; const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; -// International pre-release endpoints stay undefined until the server side -// confirms them; never derive them from the domestic naming pattern. -export const PRE_INTL_ALIYUN_AUTHORIZATION_URL: string | undefined = undefined; -export const PRE_INTL_ALIYUN_OAUTH_BASE_URL: string | undefined = undefined; +// signin/oauth come from the IMS open docs (系统应用申请 / EndPoint); console +// origin/gateway match inner-console-call's pre.singapore route. The two +// OpenAPI hosts stay undefined until the server side confirms them; never +// derive them from the domestic naming pattern. +export const PRE_INTL_ALIYUN_AUTHORIZATION_URL: string | undefined = + "https://signin.alibabacloud.com/oauth2/v1/auth"; +export const PRE_INTL_ALIYUN_OAUTH_BASE_URL: string | undefined = + "https://pre-ims-oauth-intl-share.aliyun-inc.com"; export const PRE_INTL_MODEL_STUDIO_HOST: string | undefined = undefined; export const PRE_INTL_BAILIAN_CONTROL_HOST: string | undefined = undefined; -const PRE_INTL_CONSOLE_ORIGIN: string | undefined = undefined; -const PRE_INTL_CONSOLE_GATEWAY: string | undefined = undefined; +const PRE_INTL_CONSOLE_ORIGIN: string | undefined = + "https://pre-modelstudio.console.alibabacloud.com"; +const PRE_INTL_CONSOLE_GATEWAY: string | undefined = + "https://pre-bailian-singapore-cs.alibabacloud.com"; export const PRE_INTL_ALIYUN_CLI_CLIENT_ID = "4102369295402391842"; From 65e11a7af2a7ff47c9bf3c792c63b58e6b90d09d Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Mon, 30 Nov 2026 10:27:02 +0800 Subject: [PATCH 09/13] feat(auth): enable international pre-release OAuth login with confirmed OpenAPI hosts --- docs/agents/auth-change.md | 2 +- packages/cli/README.md | 4 +- packages/cli/README.zh.md | 4 +- packages/commands/tests/auth-aliyun.test.ts | 80 ++++++++++++++++--- packages/commands/tests/e2e/auth.e2e.test.ts | 51 ++++++++---- packages/core/src/config/control-plane.ts | 37 +++++++-- packages/core/tests/control-plane.test.ts | 79 ++++++++++++++++++ .../core/tests/refresh-token-target.test.ts | 6 +- 8 files changed, 220 insertions(+), 43 deletions(-) create mode 100644 packages/core/tests/control-plane.test.ts diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index 660d97aa5..a4c4e8ddc 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -81,7 +81,7 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - OAuth 入口是 `bl auth login --oauth [--console-site ] [--console-region ]`,与 `--api-key` / `--console` / `--open-api` 并列为第四种登录模式;7 个 OAuth 专属 flag(`--client-id` / `--scope` / `--oauth-base-url` / `--authorization-url` / `--modelstudio-host` / `--console-gateway` / `--bailiancontrol-host`)定义在 `auth/aliyun-flags.ts`,脱离 `--oauth` 报用法错误。旧 `bl auth --login aliyun` 根入口已移除(仅 beta 存在过,无 stable 兼容负担);`aliyun.ts` 只保留 `runAliyunOAuthLogin` 与 loginPlan,不再是 defineCommand。 - 默认 OAuth 回调仅监听 `127.0.0.1` 随机端口的 `/oauth/callback` 路径,授权请求与换票使用同一 `redirect_uri`。IAM 登记 `http://127.0.0.1:12345/oauth/callback`;NativeApp 忽略回环端口,但协议、主机和路径必须一致,不保留根路径兼容。 - OAuth 的 `--no-browser` 显式选择跨设备手动授权:固定使用已登记的 `http://127.0.0.1:12345/oauth/callback`,不启服务器,在原进程粘贴完整回调 URL;校验地址、唯一且匹配的 state、唯一非空 code,拒绝 userinfo、fragment、非法查询编码、解码后包含控制字符的查询与其它登录会话。有可关闭回显的 TTY 时隐藏输入,非 TTY 提示上游终端可能回显;不保存输入历史。错误输入可重试但不重新生成 state/PKCE;有效 state 的授权拒绝、EOF、超长输入、Ctrl+C、Ctrl+Z 或超时结束登录。与默认流共用换票、落盘及取消处理,不自动降级、不提供设备码流程,不改变 `auth login --console --no-browser` 的本机回调语义。 -- 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile(仅同 site 复用);端点维持显式参数 > Profile > 默认地址。`--console-region` 只决定写入 config.json 的 `console_region` 与控制台路由(REGION_GATEWAYS 四组合齐全),缺省按 site 推导(domestic→cn-beijing,international→ap-southeast-1),显式值自由覆盖、不做 site×region 配对拒绝;OAuth 前三跳(signin/token/exchange)端点仅由 site 决定。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和按 site 分组的端点常量(`control-plane.ts` 的 `PRE_DOMESTIC_GROUP` / `PRE_INTL_GROUP`),不读线上控制面凭据、不隐式回退、不改 hosts/代理。国际预发 IAM 应用已获批(client ID 内置 `PRE_INTL_ALIYUN_CLI_CLIENT_ID`),其余端点占位 undefined:未确认时 live 抛 `unconfirmedIntlPreError()` 双语阻断、dry-run 计入 missing,零网络零写盘;**禁止猜测域名**,确认后填常量组即解锁(独立 commit)。国际线上应用未申请,`international × online` 硬阻断(dry-run 同样报错)。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 +- 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile(仅同 site 复用);端点维持显式参数 > Profile > 默认地址。`--console-region` 只决定写入 config.json 的 `console_region` 与控制台路由(REGION_GATEWAYS 四组合齐全),缺省按 site 推导(domestic→cn-beijing,international→ap-southeast-1),显式值自由覆盖、不做 site×region 配对拒绝;OAuth 前三跳(signin/token/exchange)端点仅由 site 决定。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和按 site 分组的端点常量(`control-plane.ts` 的 `PRE_DOMESTIC_GROUP` / `PRE_INTL_GROUP`),不读线上控制面凭据、不隐式回退、不改 hosts/代理。国际预发 IAM 应用已获批(client ID 内置 `PRE_INTL_ALIYUN_CLI_CLIENT_ID`),六端点已于 2026-11-30 全部确认填入 `PRE_INTL_GROUP`(两个 OpenAPI host 由服务端确认;OpenAPI 域名是 region 模板 `modelstudio.{region_id}.aliyuncs.com` / `bailiancontrol.{region_id}.aliyuncs.com`,不区分站点,只有控制台路由区分站点,`resolvePreOpenApiHost` 须同时接受线上区域域名与预发域名)。`intlPreEndpointsConfirmed()` 闸门保留:任一常量回退 undefined 时 live 抛 `unconfirmedIntlPreError()` 双语阻断、dry-run 计入 missing,零网络零写盘;**禁止猜测域名**,新端点仅服务端确认后填入。`BAILIAN_PRE_CONSOLE_ORIGIN/GATEWAY` 在 env 解析期只校验值属于某个已确认站点组,site×value 一致性由命令期 `requirePreEndpoint` 校验。国际线上应用未申请,`international × online` 硬阻断(dry-run 同样报错)。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 - `aliyun_oauth` 仅保存端点、client_id/scope、会话引用、域激活状态及到期元数据;OAuth AT 不覆盖旧的 Console `access_token`。凭据存于配置目录下独立的 `oauth/.json` 明文文件,绑定会话引用,不写入主配置。Unix 校验目录 `0700` 和文件 `0600` 及所有者,Windows 校验私有 ACL;拒绝非普通文件及链接,使用同目录唯一临时文件、fsync 和原子替换。旧加密会话不迁移,需要重新登录。 - 同一个异步 OpenAPI provider 负责 OAuth AT/RT→STS,Console 换票与 OpenAPI 签名前复用。优先级保持 flag > 百炼 env > 所选 file(静态或 OAuth)> 阿里云 env;临时来源不落盘。`describe/stored` 只读元数据,不读取凭据文件;静态 dry-run 不调用 OAuth,框架更新/遥测仍遵循原设置。 - `/v1/exchange` 接受完整的 PascalCase 或 camelCase STS 字段,不跨两套字段拼接。两种格式均校验非空字符串凭据及未来到期时间,不输出原始响应体。 diff --git a/packages/cli/README.md b/packages/cli/README.md index da22fc67c..5f6fe046f 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -204,7 +204,7 @@ Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. Native Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. `--console-region ` only sets the `console_region` saved to config.json and the Console routing; the OAuth authorization/token/exchange endpoints follow the site alone. It defaults to `cn-beijing` for domestic and `ap-southeast-1` for international. -International site: `bl auth login --oauth --console-site international`. The international pre-release IAM application is approved and its client ID is built in, but the remaining pre-release endpoints are not confirmed yet, so login stays blocked until they are filled in; `--dry-run` lists the missing items offline. International production login is not available yet because the production application has not been approved. +International site: `bl auth login --oauth --console-site international`. The international pre-release IAM application is approved, its client ID is built in, and all pre-release endpoints are confirmed, so pre-release login works like the domestic one. International production login is not available yet because the production application has not been approved. For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth login --oauth --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. @@ -216,7 +216,7 @@ The example reuses an already configured OAuth Profile; first online login still #### Domestic pre-release control plane -Set `BAILIAN_PRE=1` (or `true`) to select the pre-release control plane: domestic `cn-beijing`, or international `ap-southeast-1` with `--console-site international` (blocked until the international endpoint group is confirmed). Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. +Set `BAILIAN_PRE=1` (or `true`) to select the pre-release control plane: domestic `cn-beijing`, or international `ap-southeast-1` with `--console-site international`. Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. ```bash BAILIAN_PRE=1 bl auth login --oauth --dry-run diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index 115d8e0b9..7d8c1bd83 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -203,7 +203,7 @@ IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeA 线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。`--console-region ` 只决定写入 config.json 的 `console_region` 与控制台路由;OAuth 授权/换票端点仅由站点决定。缺省按站点推导:国内 `cn-beijing`,国际 `ap-southeast-1`。 -国际站:`bl auth login --oauth --console-site international`。国际预发 IAM 应用已获批,client ID 已内置;其余预发端点尚未确认,确认填入前登录保持阻断,`--dry-run` 可离线列出缺失项。国际站线上应用未申请,线上登录尚未开放。 +国际站:`bl auth login --oauth --console-site international`。国际预发 IAM 应用已获批,client ID 已内置,预发端点已全部确认,预发登录方式与国内一致。国际站线上应用未申请,线上登录尚未开放。 SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth login --oauth --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 @@ -215,7 +215,7 @@ bl auth login --oauth --config aliyun --no-browser #### 国内预发控制面 -用 `BAILIAN_PRE=1`(也接受 `true`)切换预发控制面:国内 `cn-beijing`,或配合 `--console-site international` 使用国际 `ap-southeast-1`(国际端点组确认前保持阻断);未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 +用 `BAILIAN_PRE=1`(也接受 `true`)切换预发控制面:国内 `cn-beijing`,或配合 `--console-site international` 使用国际 `ap-southeast-1`;未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 ```bash BAILIAN_PRE=1 bl auth login --oauth --dry-run diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index fbabeed24..b5297aeb8 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -11,6 +11,8 @@ import { PRE_INTL_ALIYUN_AUTHORIZATION_URL, PRE_INTL_ALIYUN_CLI_CLIENT_ID, PRE_INTL_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_MODEL_STUDIO_HOST, + PRE_INTL_BAILIAN_CONTROL_HOST, PRE_MODEL_STUDIO_HOST, PRE_BAILIAN_CONTROL_HOST, BailianError, @@ -47,6 +49,7 @@ const DEFAULT_ENDPOINTS = { consoleGateway: "https://bailian-cs.console.aliyun.com", }; const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; +const PRE_INTL_CONSOLE_GATEWAY = "https://pre-bailian-singapore-cs.alibabacloud.com"; const SECRETS = { code: "test-authorization-code-secret", accessToken: "test-oauth-access-token-secret", @@ -118,7 +121,9 @@ beforeEach(() => { const url = new URL(input instanceof Request ? input.url : input.toString()); requests.push({ url, init }); const isOAuth = - [ENDPOINTS.oauthBaseUrl, PRE_ALIYUN_OAUTH_BASE_URL].includes(url.origin) && !url.search; + [ENDPOINTS.oauthBaseUrl, PRE_ALIYUN_OAUTH_BASE_URL, PRE_INTL_ALIYUN_OAUTH_BASE_URL].includes( + url.origin, + ) && !url.search; if (isOAuth && url.pathname === "/v1/revoke") { return new Response(null, { status: revokeFails ? 503 : 200 }); } @@ -126,15 +131,21 @@ beforeEach(() => { if (isOAuth && url.pathname === "/v1/token") stage = "token"; else if (isOAuth && url.pathname === "/v1/exchange") stage = "sts"; else if ( - [ENDPOINTS.modelstudioHost, DEFAULT_ENDPOINTS.modelstudioHost, PRE_MODEL_STUDIO_HOST].some( - (hostname) => url.href === `https://${hostname}/modelstudio/cli/generateAccessToken`, - ) + [ + ENDPOINTS.modelstudioHost, + DEFAULT_ENDPOINTS.modelstudioHost, + PRE_MODEL_STUDIO_HOST, + PRE_INTL_MODEL_STUDIO_HOST, + ].some((hostname) => url.href === `https://${hostname}/modelstudio/cli/generateAccessToken`) ) stage = "generate"; else if ( - [ENDPOINTS.consoleGateway, DEFAULT_ENDPOINTS.consoleGateway, PRE_CONSOLE_GATEWAY].includes( - url.origin, - ) && + [ + ENDPOINTS.consoleGateway, + DEFAULT_ENDPOINTS.consoleGateway, + PRE_CONSOLE_GATEWAY, + PRE_INTL_CONSOLE_GATEWAY, + ].includes(url.origin) && url.pathname === "/cli/api.json" ) stage = "gateway"; @@ -1383,7 +1394,7 @@ test.each([false, true])( }, ); -test("国际预发端点未确认时 live 阻断,零监听零请求零落盘", async () => { +test("国际预发 live 缺网关时阻断,零监听零请求零落盘", async () => { const listen = vi.spyOn(http.Server.prototype, "listen"); const probe = launch( { consoleSite: "international" }, @@ -1391,7 +1402,9 @@ test("国际预发端点未确认时 live 阻断,零监听零请求零落盘", ); expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE, - message: expect.stringContaining("International pre-release endpoints are not confirmed yet"), + message: expect.stringContaining( + "Set BAILIAN_PRE_CONSOLE_GATEWAY to the confirmed international pre-release CLI gateway", + ), }); expect(listen).not.toHaveBeenCalled(); expect(probe.browser).not.toHaveBeenCalled(); @@ -1399,7 +1412,34 @@ test("国际预发端点未确认时 live 阻断,零监听零请求零落盘", expect(probe.save).not.toHaveBeenCalled(); }); -test("国际预发 dry-run 离线计入缺失端点,给出内置 clientId 与 ap-southeast-1", async () => { +test("国际预发 OAuth 登录绑定国际预设端点,不请求国内或线上网关", async () => { + const probe = launch( + { consoleSite: "international" }, + { omitEndpoints: true, preControlPlane: { consoleGateway: PRE_INTL_CONSOLE_GATEWAY } }, + ); + const { authUrl } = await finish(probe); + expect(new URL(authUrl).origin).toBe(new URL(PRE_INTL_ALIYUN_AUTHORIZATION_URL!).origin); + expect(requests.map(({ url }) => url.origin)).toEqual([ + PRE_INTL_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_ALIYUN_OAUTH_BASE_URL, + `https://${PRE_INTL_MODEL_STUDIO_HOST}`, + PRE_INTL_CONSOLE_GATEWAY, + ]); + expect(probe.save).toHaveBeenCalledWith( + expect.objectContaining({ + client_id: PRE_INTL_ALIYUN_CLI_CLIENT_ID, + console_site: "international", + console_region: "ap-southeast-1", + modelstudio_host: PRE_INTL_MODEL_STUDIO_HOST, + console_gateway: PRE_INTL_CONSOLE_GATEWAY, + bailiancontrol_host: PRE_INTL_BAILIAN_CONTROL_HOST, + }), + expect.any(Object), + ); + assertNoSecrets(probe); +}); + +test("国际预发 dry-run 离线计入缺失网关,给出内置 clientId 与 ap-southeast-1", async () => { const probe = launch( { consoleSite: "international" }, { dryRun: true, omitEndpoints: true, preControlPlane: {} }, @@ -1418,13 +1458,31 @@ test("国际预发 dry-run 离线计入缺失端点,给出内置 clientId 与 }); expect(data.plan.authorization_url).toBe(PRE_INTL_ALIYUN_AUTHORIZATION_URL); expect(data.plan.oauth_base_url).toBe(PRE_INTL_ALIYUN_OAUTH_BASE_URL); - expect(data.plan.modelstudio_host).toBeUndefined(); + expect(data.plan.modelstudio_host).toBe(PRE_INTL_MODEL_STUDIO_HOST); + expect(data.plan.bailiancontrol_host).toBe(PRE_INTL_BAILIAN_CONTROL_HOST); expect(data.plan.console_gateway).toBeUndefined(); expect(probe.describe).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled(); expect(probe.save).not.toHaveBeenCalled(); }); +test("国际预发 dry-run 配齐可信网关后 missing 为空", async () => { + const probe = launch( + { consoleSite: "international" }, + { + dryRun: true, + omitEndpoints: true, + preControlPlane: { consoleGateway: PRE_INTL_CONSOLE_GATEWAY }, + }, + ); + expect(await probe.outcome).toBeUndefined(); + const data = JSON.parse(probe.stdout.join("")); + expect(data.missing).toEqual([]); + expect(data.plan.console_gateway).toBe(PRE_INTL_CONSOLE_GATEWAY); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + test("dry-run 地域缺省按 site 推导,显式覆盖切换默认 POP/网关但不改 OAuth 端点", async () => { const domestic = launch({}, { dryRun: true, omitEndpoints: true }); expect(await domestic.outcome).toBeUndefined(); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index 8d67927b6..7747bed2f 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -213,29 +213,28 @@ describe("e2e: auth", () => { expect(result.stderr).toContain("国际站线上 OAuth 登录尚未开放"); }); - test("国际预发端点未确认:live 阻断,dry-run 离线列出缺失端点", async () => { + test("国际预发:缺网关 live 阻断,dry-run 离线列出缺失项,配齐网关后 missing 为空", async () => { const live = await runCommandInProcess( AUTH_ROUTES, ["auth", "login", "--oauth", "--console-site", "international", "--output", "json"], { BAILIAN_PRE: "1" }, ); expect(live.exitCode).toBe(2); - expect(live.stderr).toContain("International pre-release endpoints are not confirmed yet"); - - const dryRun = await runCommandInProcess( - AUTH_ROUTES, - [ - "auth", - "login", - "--oauth", - "--console-site", - "international", - "--dry-run", - "--output", - "json", - ], - { BAILIAN_PRE: "1" }, + expect(live.stderr).toContain( + "Set BAILIAN_PRE_CONSOLE_GATEWAY to the confirmed international pre-release CLI gateway", ); + + const dryRunArgs = [ + "auth", + "login", + "--oauth", + "--console-site", + "international", + "--dry-run", + "--output", + "json", + ]; + const dryRun = await runCommandInProcess(AUTH_ROUTES, dryRunArgs, { BAILIAN_PRE: "1" }); expect(dryRun.exitCode, dryRun.stderr).toBe(0); const data = parseStdoutJson<{ environment: string; @@ -245,6 +244,9 @@ describe("e2e: auth", () => { console_site: string; authorization_url: string; oauth_base_url: string; + modelstudio_host: string; + bailiancontrol_host: string; + console_gateway?: string; }; missing: string[]; }>(dryRun.stdout); @@ -254,7 +256,24 @@ describe("e2e: auth", () => { expect(data.plan.console_site).toBe("international"); expect(data.plan.authorization_url).toBe("https://signin.alibabacloud.com/oauth2/v1/auth"); expect(data.plan.oauth_base_url).toBe("https://pre-ims-oauth-intl-share.aliyun-inc.com"); + expect(data.plan.modelstudio_host).toBe("modelstudio-pre.ap-southeast-1.aliyuncs.com"); + expect(data.plan.bailiancontrol_host).toBe("bailiancontrol-pre.ap-southeast-1.aliyuncs.com"); + expect(data.plan.console_gateway).toBeUndefined(); expect(data.missing).toEqual(["BAILIAN_PRE_CONSOLE_GATEWAY"]); + + const complete = await runCommandInProcess(AUTH_ROUTES, dryRunArgs, { + BAILIAN_PRE: "1", + BAILIAN_PRE_CONSOLE_GATEWAY: "https://pre-bailian-singapore-cs.alibabacloud.com", + }); + expect(complete.exitCode, complete.stderr).toBe(0); + const completeData = parseStdoutJson<{ + plan: { console_gateway: string }; + missing: string[]; + }>(complete.stdout); + expect(completeData.plan.console_gateway).toBe( + "https://pre-bailian-singapore-cs.alibabacloud.com", + ); + expect(completeData.missing).toEqual([]); }); test("auth login 模式专属参数不能脱离对应模式", async () => { diff --git a/packages/core/src/config/control-plane.ts b/packages/core/src/config/control-plane.ts index ca1f03c4c..aa1ff133c 100644 --- a/packages/core/src/config/control-plane.ts +++ b/packages/core/src/config/control-plane.ts @@ -11,15 +11,18 @@ const PRE_CONSOLE_ORIGIN = "https://pre-bailian.console.aliyun.com"; const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; // signin/oauth come from the IMS open docs (系统应用申请 / EndPoint); console -// origin/gateway match inner-console-call's pre.singapore route. The two -// OpenAPI hosts stay undefined until the server side confirms them; never -// derive them from the domestic naming pattern. +// origin/gateway match inner-console-call's pre.singapore route; the two +// OpenAPI hosts were confirmed by the server side on 2026-11-30. OpenAPI +// hosts are region-templated and site-independent; only console routing +// distinguishes sites. export const PRE_INTL_ALIYUN_AUTHORIZATION_URL: string | undefined = "https://signin.alibabacloud.com/oauth2/v1/auth"; export const PRE_INTL_ALIYUN_OAUTH_BASE_URL: string | undefined = "https://pre-ims-oauth-intl-share.aliyun-inc.com"; -export const PRE_INTL_MODEL_STUDIO_HOST: string | undefined = undefined; -export const PRE_INTL_BAILIAN_CONTROL_HOST: string | undefined = undefined; +export const PRE_INTL_MODEL_STUDIO_HOST: string | undefined = + "modelstudio-pre.ap-southeast-1.aliyuncs.com"; +export const PRE_INTL_BAILIAN_CONTROL_HOST: string | undefined = + "bailiancontrol-pre.ap-southeast-1.aliyuncs.com"; const PRE_INTL_CONSOLE_ORIGIN: string | undefined = "https://pre-modelstudio.console.alibabacloud.com"; const PRE_INTL_CONSOLE_GATEWAY: string | undefined = @@ -93,11 +96,25 @@ export function resolvePreControlPlane(env: NodeJS.ProcessEnv): PreControlPlane ...(consoleOrigin ? { consoleOrigin: normalizeOAuthUrl(consoleOrigin, true) } : {}), ...(consoleGateway ? { consoleGateway: normalizeOAuthUrl(consoleGateway, true) } : {}), }; - if (settings.consoleOrigin) requirePreConsoleOrigin(settings, {}); - if (settings.consoleGateway) requirePreConsoleGateway(settings, {}); + // The site is unknown at env-parse time; accept either confirmed group here + // and let requirePreEndpoint enforce the site×value match per command. + if (settings.consoleOrigin) requireConfirmedPreValue(settings.consoleOrigin, "consoleOrigin"); + if (settings.consoleGateway) requireConfirmedPreValue(settings.consoleGateway, "consoleGateway"); return settings; } +function requireConfirmedPreValue( + configured: string, + kind: "consoleOrigin" | "consoleGateway", +): void { + if (configured === PRE_DOMESTIC_GROUP[kind] || configured === PRE_INTL_GROUP[kind]) return; + const flag = + kind === "consoleOrigin" ? "BAILIAN_PRE_CONSOLE_ORIGIN" : "BAILIAN_PRE_CONSOLE_GATEWAY"; + throw new UsageError( + `${flag} must match a confirmed pre-release endpoint. / ${flag} 必须与已确认的预发端点一致。`, + ); +} + /** Site×region combination check only; does not require confirmed intl endpoints. */ export function validatePreConsoleRegion(target: { region?: string; site?: string }): void { const site = target.site ?? "domestic"; @@ -175,7 +192,11 @@ export function resolvePreOpenApiHost(host: string): string { ) { return PRE_INTL_MODEL_STUDIO_HOST; } - if (PRE_INTL_BAILIAN_CONTROL_HOST !== undefined && host === PRE_INTL_BAILIAN_CONTROL_HOST) { + if ( + PRE_INTL_BAILIAN_CONTROL_HOST !== undefined && + (host === "bailiancontrol.ap-southeast-1.aliyuncs.com" || + host === PRE_INTL_BAILIAN_CONTROL_HOST) + ) { return PRE_INTL_BAILIAN_CONTROL_HOST; } throw new UsageError( diff --git a/packages/core/tests/control-plane.test.ts b/packages/core/tests/control-plane.test.ts new file mode 100644 index 000000000..331b285eb --- /dev/null +++ b/packages/core/tests/control-plane.test.ts @@ -0,0 +1,79 @@ +import { expect, test } from "vite-plus/test"; +import { + requirePreConsoleGateway, + resolvePreControlPlane, + resolvePreOpenApiHost, +} from "../src/config/control-plane.ts"; +import { UsageError } from "../src/errors/base.ts"; + +const DOMESTIC_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; +const INTL_GATEWAY = "https://pre-bailian-singapore-cs.alibabacloud.com"; +const INTL_ORIGIN = "https://pre-modelstudio.console.alibabacloud.com"; + +test("env 解析接受国内与国际两组可信 origin/gateway", () => { + expect( + resolvePreControlPlane({ + BAILIAN_PRE: "1", + BAILIAN_PRE_CONSOLE_ORIGIN: INTL_ORIGIN, + BAILIAN_PRE_CONSOLE_GATEWAY: INTL_GATEWAY, + }), + ).toEqual({ consoleOrigin: INTL_ORIGIN, consoleGateway: INTL_GATEWAY }); + expect( + resolvePreControlPlane({ BAILIAN_PRE: "1", BAILIAN_PRE_CONSOLE_GATEWAY: DOMESTIC_GATEWAY }), + ).toEqual({ consoleGateway: DOMESTIC_GATEWAY }); +}); + +test("env 解析拒绝未确认的 origin/gateway 值", () => { + expect(() => + resolvePreControlPlane({ + BAILIAN_PRE: "1", + BAILIAN_PRE_CONSOLE_GATEWAY: "https://evil.example.com", + }), + ).toThrow("BAILIAN_PRE_CONSOLE_GATEWAY must match a confirmed pre-release endpoint"); + expect(() => + resolvePreControlPlane({ + BAILIAN_PRE: "1", + BAILIAN_PRE_CONSOLE_ORIGIN: "https://evil.example.com", + }), + ).toThrow(UsageError); +}); + +test("命令期校验 site×gateway 一致性:国际网关配国内站点拒绝", () => { + expect( + requirePreConsoleGateway({ consoleGateway: INTL_GATEWAY }, { site: "international" }), + ).toBe(INTL_GATEWAY); + expect(() => + requirePreConsoleGateway({ consoleGateway: INTL_GATEWAY }, { site: "domestic" }), + ).toThrow("Set BAILIAN_PRE_CONSOLE_GATEWAY to the confirmed domestic pre-release CLI gateway"); + expect(() => requirePreConsoleGateway({}, { site: "international" })).toThrow( + "Set BAILIAN_PRE_CONSOLE_GATEWAY to the confirmed international pre-release CLI gateway", + ); +}); + +test("OpenAPI 域名按 region 模板映射到预发,不区分站点", () => { + expect(resolvePreOpenApiHost("modelstudio.aliyuncs.com")).toBe("modelstudio-pre.aliyuncs.com"); + expect(resolvePreOpenApiHost("modelstudio.cn-beijing.aliyuncs.com")).toBe( + "modelstudio-pre.aliyuncs.com", + ); + expect(resolvePreOpenApiHost("bailiancontrol.cn-beijing.aliyuncs.com")).toBe( + "bailiancontrol-pre.aliyuncs.com", + ); + expect(resolvePreOpenApiHost("modelstudio.ap-southeast-1.aliyuncs.com")).toBe( + "modelstudio-pre.ap-southeast-1.aliyuncs.com", + ); + expect(resolvePreOpenApiHost("bailiancontrol.ap-southeast-1.aliyuncs.com")).toBe( + "bailiancontrol-pre.ap-southeast-1.aliyuncs.com", + ); +}); + +test("预发 OpenAPI 域名映射到自身,未知域名拒绝", () => { + expect(resolvePreOpenApiHost("modelstudio-pre.ap-southeast-1.aliyuncs.com")).toBe( + "modelstudio-pre.ap-southeast-1.aliyuncs.com", + ); + expect(resolvePreOpenApiHost("bailiancontrol-pre.ap-southeast-1.aliyuncs.com")).toBe( + "bailiancontrol-pre.ap-southeast-1.aliyuncs.com", + ); + expect(() => resolvePreOpenApiHost("modelstudio.cn-hangzhou.aliyuncs.com")).toThrow( + "not available in the pre-release control plane", + ); +}); diff --git a/packages/core/tests/refresh-token-target.test.ts b/packages/core/tests/refresh-token-target.test.ts index aa04c0a1f..108a05f0a 100644 --- a/packages/core/tests/refresh-token-target.test.ts +++ b/packages/core/tests/refresh-token-target.test.ts @@ -20,10 +20,10 @@ test("预发显式国内地域放行,跨地域组合拒绝", () => { ).toThrow(UsageError); }); -test("预发国际站端点未确认时阻断,错误地域组合优先拒绝", () => { - expect(() => +test("预发国际站按 ap-southeast-1 解析,错误地域组合拒绝", () => { + expect( resolveCLIAccessTokenTarget({ consoleSite: "international", preControlPlane: {} }, BASE_URL), - ).toThrow("International pre-release endpoints are not confirmed yet"); + ).toEqual({ region: "ap-southeast-1", site: "international" }); expect(() => resolveCLIAccessTokenTarget( { consoleSite: "international", consoleRegion: "cn-beijing", preControlPlane: {} }, From f07c6ddda217aabdacb0e55c9f04d0aa98bf5d59 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Mon, 30 Nov 2026 11:52:18 +0800 Subject: [PATCH 10/13] fix(auth): address CR findings on workspace init auth domain and OAuth recovery Restore workspace init to auth:none with explicit AK flags while keeping pre-release gateway routing; add tolerateInvalidOAuth recovery reads so a corrupted aliyun_oauth block no longer bricks logout/re-login/config set; drop the unverified 30-day console session claim from auth login --oauth. --- packages/commands/src/commands/auth/login.ts | 4 +- .../commands/src/commands/workspace/init.ts | 88 ++++++++++++++++--- ...atalog-workspace-permission-output.test.ts | 28 ++---- packages/core/src/auth/store.ts | 76 +++++++++++----- packages/core/src/config/loader.ts | 16 +++- packages/core/src/config/schema.ts | 22 ++++- packages/core/src/config/store.ts | 4 +- packages/core/tests/config-store.test.ts | 40 +++++++++ skills/bailian-cli/reference/auth.md | 2 +- skills/bailian-cli/reference/index.md | 2 +- skills/bailian-cli/reference/workspace.md | 28 +++--- 11 files changed, 229 insertions(+), 81 deletions(-) diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index 6c002827b..df761bb8d 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -139,9 +139,9 @@ export default defineCommand({ type: "switch", description: { "en-US": - "Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a 30-day console session with automatic renewal", + "Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a console session with automatic renewal", "zh-CN": - "通过阿里云 OAuth 登录(默认中国站;国际站使用 --console-site international)。换取 30 天控制台会话并自动续期", + "通过阿里云 OAuth 登录(默认中国站;国际站使用 --console-site international)。换取控制台会话并自动续期", }, }, ...ALIYUN_OAUTH_LOGIN_FLAGS, diff --git a/packages/commands/src/commands/workspace/init.ts b/packages/commands/src/commands/workspace/init.ts index eda59cffc..92f01870a 100644 --- a/packages/commands/src/commands/workspace/init.ts +++ b/packages/commands/src/commands/workspace/init.ts @@ -2,13 +2,17 @@ import { defineCommand, BailianError, ExitCode, + generateCLIAccessToken, + callConsoleGateway, + effectiveConsoleGatewayConfig, PRE_BAILIAN_CONTROL_HOST, PRE_MODEL_STUDIO_HOST, - effectiveConsoleGatewayConfig, requirePreConsoleGateway, createBailianControlUser, listBailianControlWorkspaces, resetBailianControlPolicies4Agent, + type ConsoleGatewayTarget, + type FlagsDef, type CommandContext, } from "bailian-cli-core"; @@ -20,6 +24,30 @@ const API = { buyCommodity: "zeldaEasy.bailian-commerce.bill.buyPostpaidCommodity", } as const; +const FLAGS = { + accessKeyId: { + type: "string", + valueHint: "", + description: { "en-US": "Alibaba Cloud Access Key ID", "zh-CN": "阿里云 Access Key ID" }, + }, + accessKeySecret: { + type: "string", + valueHint: "", + description: { + "en-US": "Alibaba Cloud Access Key Secret", + "zh-CN": "阿里云 Access Key Secret", + }, + }, + securityToken: { + type: "string", + valueHint: "", + description: { + "en-US": "Alibaba Cloud STS Security Token (optional)", + "zh-CN": "阿里云 STS Security Token(可选)", + }, + }, +} satisfies FlagsDef; + const POLL_INTERVAL_MS = 1000; const MAX_POLL_ATTEMPTS = 20; @@ -55,11 +83,12 @@ export default defineCommand({ "en-US": "Initialize Bailian workspace and activate postpaid services", "zh-CN": "初始化百炼 Workspace 并开通后付费服务", }, - auth: "openapi", - usageArgs: "[flags]", - exampleArgs: ["", "--access-key-id LTAIxxxxx --access-key-secret xxxxx"], + auth: "none", + usageArgs: "--access-key-id --access-key-secret [--security-token ]", + flags: FLAGS, + exampleArgs: ["--access-key-id LTAIxxxxx --access-key-secret xxxxx"], async run(ctx) { - const { settings } = ctx; + const { settings, flags } = ctx; const pre = settings.preControlPlane; const gateway = effectiveConsoleGatewayConfig(settings); const consoleTarget = { region: gateway.consoleRegion, site: gateway.consoleSite }; @@ -131,14 +160,47 @@ export default defineCommand({ return; } - // Both domains must be routable before initSpace, OpenAPI writes, or purchases. - if (pre) { - requirePreConsoleGateway(pre, consoleTarget); - ctx.client.resolveOpenApiHost(PRE_MODEL_STUDIO_HOST); + const { accessKeyId, accessKeySecret } = flags; + if (!accessKeyId || !accessKeySecret) { + throw new BailianError( + "workspace init requires --access-key-id and --access-key-secret.", + ExitCode.USAGE, + ); + } + const securityToken = flags.securityToken || undefined; + + // Step 0: Exchange AK/SK for a temporary CLI access token used by console calls. + const tokenResp = await generateCLIAccessToken({ + identity: ctx.identity, + settings: { ...settings, consoleRegion: gateway.consoleRegion }, + debug: (diagnostic) => ctx.output.debug(diagnostic), + baseUrl: ctx.client.baseUrl, + accessKeyId, + accessKeySecret, + securityToken, + }); + const accessToken: string | undefined = tokenResp.cliAccessToken; + if (!accessToken) { + throw new BailianError("Failed to generate CLI access token from AK/SK.", ExitCode.GENERAL); } - ctx.client.resolveOpenApiHost(`bailiancontrol.${gateway.consoleRegion}.aliyuncs.com`); + + const target: ConsoleGatewayTarget = { + region: gateway.consoleRegion, + site: gateway.consoleSite, + ...(gateway.consoleSwitchAgent != null ? { switchAgent: gateway.consoleSwitchAgent } : {}), + token: accessToken, + }; + const callApi = (api: string, data: Record = {}) => - ctx.client.console(api, data); + callConsoleGateway( + target, + settings.timeout, + { api, data }, + { + debug: (diagnostic) => ctx.output.debug(diagnostic), + preControlPlane: pre, + }, + ); // Step 1: Check login info ctx.output.info({ @@ -169,7 +231,9 @@ export default defineCommand({ debug: (diagnostic: Parameters[0]) => ctx.output.debug(diagnostic), baseUrl: ctx.client.baseUrl, regionId: gateway.consoleRegion, - client: ctx.client, + accessKeyId, + accessKeySecret, + securityToken, }; try { diff --git a/packages/commands/tests/output/catalog-workspace-permission-output.test.ts b/packages/commands/tests/output/catalog-workspace-permission-output.test.ts index da02f76f6..c8fe09cd7 100644 --- a/packages/commands/tests/output/catalog-workspace-permission-output.test.ts +++ b/packages/commands/tests/output/catalog-workspace-permission-output.test.ts @@ -332,31 +332,17 @@ async function invoke(scenario: Scenario, display: Display, flags = scenario.fla }, }, }); - const mixedOpenApi = scenario.command.auth === "openapi"; - const openApiCredential = { - source: "flag" as const, - accessKeyId: "fixture-access-key", - accessKeySecret: "fixture-access-secret", - securityToken: "fixture-security-token", - }; const client = new Client({ identity, - settings: mixedOpenApi - ? { ...settings, consoleRegion: "cn-beijing", consoleSite: "domestic" } - : settings, + settings, baseUrl: "https://fixture.invalid", - ...(mixedOpenApi - ? { openApiCred: openApiCredential, resolveConsoleOpenApiCredential: () => openApiCredential } - : {}), apiCred: { token: "fixture-api-token", source: "flag", baseUrl: "https://fixture.invalid" }, - consoleCred: mixedOpenApi - ? undefined - : { - token: "fixture-console-token", - region: "cn-beijing", - site: "domestic", - source: "flag", - }, + consoleCred: { + token: "fixture-console-token", + region: "cn-beijing", + site: "domestic", + source: "flag", + }, debug: (record) => reporter.output.debug(record), }); let exitCode = 0; diff --git a/packages/core/src/auth/store.ts b/packages/core/src/auth/store.ts index f74a98964..2389dabe7 100644 --- a/packages/core/src/auth/store.ts +++ b/packages/core/src/auth/store.ts @@ -12,7 +12,7 @@ import { assertOAuthConfiguration, } from "./openapi-provider.ts"; import { revokeAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; -import { profileSite } from "./aliyun-config.ts"; +import { profileSite, parseAliyunOAuthProfile } from "./aliyun-config.ts"; import type { AliyunOAuthProfile, AliyunOAuthSession } from "./aliyun-types.ts"; import { CredentialError } from "../errors/credential.ts"; import { getConfigPath } from "../config/paths.ts"; @@ -101,6 +101,18 @@ export function makeAuthStore( const configurationPath = sources.configPath ?? getConfigPath(pre); const directory = options.directory ?? dirname(configurationPath); const readBoundConfig = (name = configName) => readConfigFile(name, configurationPath); + // Recovery reads/writes tolerate a corrupted aliyun_oauth block so logout and + // re-login stay usable; normal reads stay strict to surface the corruption. + const readRecoverableConfig = () => + readConfigFile(configName, configurationPath, { tolerateInvalidOAuth: true }); + const strictOAuthProfile = (value: unknown): AliyunOAuthProfile | undefined => { + if (value === undefined) return undefined; + try { + return parseAliyunOAuthProfile(value); + } catch { + return undefined; + } + }; let secretStore = options.store; const getSecretStore = () => (secretStore ??= createOAuthSecretStore(directory)); return { @@ -110,7 +122,7 @@ export function makeAuthStore( // held, so behavior is unchanged. describe: () => describeAuthState({ ...sources, file: readBoundConfig() }), stored() { - const file = readBoundConfig(); + const file = readRecoverableConfig(); return { apiKey: !!file.api_key, console: !!(file.access_token || file.aliyun_oauth?.console_enabled), @@ -155,7 +167,7 @@ export function makeAuthStore( return existing as ConfigFile; }, targetConfigName, - { activate: shouldActivate, path: configurationPath }, + { activate: shouldActivate, path: configurationPath, tolerateInvalidOAuth: true }, ); }, async loginAliyun(profile, session) { @@ -181,7 +193,7 @@ export function makeAuthStore( try { await mutateConfigFile( (current) => { - previous = current.aliyun_oauth; + previous = strictOAuthProfile(current.aliyun_oauth); return { ...current, aliyun_oauth: metadata, @@ -191,7 +203,7 @@ export function makeAuthStore( }; }, configName, - { activate: activateAfterLogin, path: configurationPath }, + { activate: activateAfterLogin, path: configurationPath, tolerateInvalidOAuth: true }, ); } catch (error) { await getSecretStore() @@ -217,8 +229,9 @@ export function makeAuthStore( } }, async logout(scope) { - const profile = readBoundConfig().aliyun_oauth; - const reference = profile?.session_ref; + const profile = readRecoverableConfig().aliyun_oauth; + const validProfile = strictOAuthProfile(profile); + const reference = validProfile?.session_ref; const removeOAuth = scope === "all" || scope === "aliyun"; const keys = pre && scope === "all" @@ -232,8 +245,19 @@ export function makeAuthStore( const clearConfig = () => mutateConfigFile( (current) => { - if (current.aliyun_oauth?.session_ref !== reference) throw changedSession(); - if (!reference && !keys.some((key) => current[key] !== undefined)) return undefined; + if (validProfile) { + if (current.aliyun_oauth?.session_ref !== reference) throw changedSession(); + } else if (strictOAuthProfile(current.aliyun_oauth)) { + throw changedSession(); + } + const invalidOAuthPresent = + current.aliyun_oauth !== undefined && !strictOAuthProfile(current.aliyun_oauth); + if ( + !reference && + !invalidOAuthPresent && + !keys.some((key) => current[key] !== undefined) + ) + return undefined; const existing = { ...current }; for (const key of keys) delete existing[key]; if (removeOAuth) delete existing.aliyun_oauth; @@ -246,32 +270,44 @@ export function makeAuthStore( return existing; }, configName, - { path: configurationPath }, + { path: configurationPath, tolerateInvalidOAuth: true }, ); if (!profile || scope === "openapi") return clearConfig(); - return withFileLock(oauthSessionLockPath(directory, profile.session_ref), async () => { - const current = readBoundConfig().aliyun_oauth; - if (current?.session_ref !== profile.session_ref) throw changedSession(); - if (pre) validatePreAliyunProfile(current); - const raw = await getSecretStore().read(profile.session_ref); + if (!validProfile) { + // A corrupted profile cannot be revoked; drop its secret by raw reference. + const rawReference = + typeof profile.session_ref === "string" ? profile.session_ref : undefined; + if (removeOAuth && rawReference) + await getSecretStore() + .remove(rawReference) + .catch(() => {}); + return clearConfig(); + } + const sessionReference = validProfile.session_ref; + return withFileLock(oauthSessionLockPath(directory, sessionReference), async () => { + const current = readRecoverableConfig().aliyun_oauth; + if (current?.session_ref !== sessionReference) throw changedSession(); + const currentValid = strictOAuthProfile(current); + if (pre && currentValid) validatePreAliyunProfile(currentValid); + const raw = await getSecretStore().read(sessionReference); if (removeOAuth) { - if (raw) { + if (raw && currentValid) { const session = parseOAuthSession(raw); - assertOAuthConfiguration(current, session); + assertOAuthConfiguration(currentValid, session); if (session.refreshToken) { if (!oauthDeps) throw new CredentialError( "missing-aliyun-session", "OAuth logout requires OAuth transport dependencies. / OAuth 退出需要 OAuth 传输配置。", ); - await revokeAliyunTokens(current, session.refreshToken, oauthDeps); + await revokeAliyunTokens(currentValid, session.refreshToken, oauthDeps); } } - await getSecretStore().remove(profile.session_ref); + await getSecretStore().remove(sessionReference); } else if (raw) { const session = parseOAuthSession(raw); await getSecretStore().write( - profile.session_ref, + sessionReference, JSON.stringify({ ...session, consoleTokens: {} }), ); } diff --git a/packages/core/src/config/loader.ts b/packages/core/src/config/loader.ts index 5ed9b5357..34b2ebe2f 100644 --- a/packages/core/src/config/loader.ts +++ b/packages/core/src/config/loader.ts @@ -126,9 +126,13 @@ function readRawConfigBlock(raw: Record, configName?: string): return isConfigBlock(block) ? block : {}; } -export function readConfigFile(configName?: string, path = getConfigPath()): ConfigFile { +export function readConfigFile( + configName?: string, + path = getConfigPath(), + options: { tolerateInvalidOAuth?: boolean } = {}, +): ConfigFile { const raw = readRawConfigObject(path); - return parseConfigFile(readRawConfigBlock(raw, configName)); + return parseConfigFile(readRawConfigBlock(raw, configName), options); } /** 写入所选 Profile;登录流程可在同一次原子写入中将显式 Profile 设为激活项。 */ @@ -143,14 +147,18 @@ export async function writeConfigFile( export async function mutateConfigFile( update: (current: ConfigFile) => ConfigFile | undefined, configName?: string, - options: { activate?: boolean; path?: string } = {}, + options: { activate?: boolean; path?: string; tolerateInvalidOAuth?: boolean } = {}, ): Promise { const path = options.path ?? getConfigPath(); if (configName === CONTROL_ENVIRONMENT_KEY) normalizeConfigName(configName); await ensureConfigDir(dirname(path)); return withFileLock(`${path}.lock`, async () => { const raw = readRawConfigObject(path); - const next = update(parseConfigFile(readRawConfigBlock(raw, configName))); + const next = update( + parseConfigFile(readRawConfigBlock(raw, configName), { + tolerateInvalidOAuth: options.tolerateInvalidOAuth, + }), + ); if (next === undefined) return false; if (Object.hasOwn(next, CONTROL_ENVIRONMENT_KEY)) { throw new BailianError( diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts index b803f36db..6e7772a84 100644 --- a/packages/core/src/config/schema.ts +++ b/packages/core/src/config/schema.ts @@ -2,6 +2,7 @@ import { normalizeModelBaseUrl } from "./model-base-url.ts"; import { parseAliyunOAuthProfile } from "../auth/aliyun-config.ts"; import type { AliyunOAuthProfile } from "../auth/aliyun-types.ts"; import type { PreControlPlane } from "./control-plane.ts"; +import { UsageError } from "../errors/base.ts"; export const REGIONS = { cn: "https://dashscope.aliyuncs.com", @@ -126,11 +127,28 @@ function parseModelBaseUrl(value: string): string | undefined { } } -export function parseConfigFile(raw: unknown): ConfigFile { +export function parseConfigFile( + raw: unknown, + options: { tolerateInvalidOAuth?: boolean } = {}, +): ConfigFile { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const obj = raw as Record; const out: ConfigFile = {}; - if (obj.aliyun_oauth !== undefined) out.aliyun_oauth = parseAliyunOAuthProfile(obj.aliyun_oauth); + if (obj.aliyun_oauth !== undefined) { + try { + out.aliyun_oauth = parseAliyunOAuthProfile(obj.aliyun_oauth); + } catch (error) { + if (!options.tolerateInvalidOAuth || !(error instanceof UsageError)) throw error; + // Recovery-only: keep an invalid object block as-is so logout/re-login can + // remove or replace it; non-object garbage is dropped. + if ( + obj.aliyun_oauth && + typeof obj.aliyun_oauth === "object" && + !Array.isArray(obj.aliyun_oauth) + ) + out.aliyun_oauth = obj.aliyun_oauth as AliyunOAuthProfile; + } + } if ( typeof obj.language === "string" && diff --git a/packages/core/src/config/store.ts b/packages/core/src/config/store.ts index adbc5d3e2..53eb7319b 100644 --- a/packages/core/src/config/store.ts +++ b/packages/core/src/config/store.ts @@ -47,7 +47,7 @@ export function makeConfigStore( return existing as ConfigFile; }, configName, - { path: configurationPath }, + { path: configurationPath, tolerateInvalidOAuth: true }, ); }, async unset(keys) { @@ -58,7 +58,7 @@ export function makeConfigStore( return existing; }, configName, - { path: configurationPath }, + { path: configurationPath, tolerateInvalidOAuth: true }, ); }, profiles: () => readConfigProfiles(configurationPath), diff --git a/packages/core/tests/config-store.test.ts b/packages/core/tests/config-store.test.ts index d2f2194b8..ac1248492 100644 --- a/packages/core/tests/config-store.test.ts +++ b/packages/core/tests/config-store.test.ts @@ -495,6 +495,46 @@ test("ConfigStore:命名 config 与默认配置隔离且写入保留其它 block }); }); +test("aliyun_oauth 块损坏时 logout/config 写入可恢复,常规读取仍报错", async () => { + await inTempConfigDir(async () => { + const corrupted = { client_id: "4001958595402383681", session_ref: "not-a-uuid" }; + writeFileSync(getConfigPath(), JSON.stringify({ api_key: "sk-1", aliyun_oauth: corrupted })); + expect(() => readConfigFile()).toThrow("aliyun_oauth"); + + const store = makeAuthStore({ flags: {}, file: {}, env: {} }); + expect(store.stored()).toMatchObject({ apiKey: true, aliyunOAuth: true }); + + // 无关 config 写入保留损坏块原样,不被严格解析卡死。 + await makeConfigStore().write({ output: "json" }); + expect(JSON.parse(readFileSync(getConfigPath(), "utf8")).aliyun_oauth).toEqual(corrupted); + + // console 域退出只停用对应域,损坏块保留。 + expect(await store.logout("console")).toBe(true); + expect(JSON.parse(readFileSync(getConfigPath(), "utf8")).aliyun_oauth).toMatchObject({ + ...corrupted, + console_enabled: false, + }); + + // --aliyun 退出移除损坏块;无有效会话即无 revoke(缺 oauthDeps 也不会抛)。 + expect(await store.logout("aliyun")).toBe(true); + const after = JSON.parse(readFileSync(getConfigPath(), "utf8")); + expect(after.aliyun_oauth).toBeUndefined(); + expect(after.api_key).toBe("sk-1"); + }); +}); + +test("aliyun_oauth 为非对象垃圾时容错读取丢弃,logout 可清除", async () => { + await inTempConfigDir(async () => { + writeFileSync(getConfigPath(), JSON.stringify({ api_key: "sk-1", aliyun_oauth: "garbage" })); + const store = makeAuthStore({ flags: {}, file: {}, env: {} }); + expect(store.stored().aliyunOAuth).toBeUndefined(); + expect(await store.logout("all")).toBe(true); + const after = JSON.parse(readFileSync(getConfigPath(), "utf8")); + expect(after.aliyun_oauth).toBeUndefined(); + expect(after.api_key).toBeUndefined(); + }); +}); + test("AuthStore:login/logout 只影响当前命名 config", async () => { await inTempConfigDir(async () => { await writeConfigFile({ api_key: "sk-default", access_token: "tok-default" }); diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index 029ea3254..5129cbe15 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -64,7 +64,7 @@ bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxx | `--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 | Open the AccessKey setup guide, or save keys when --access-key-id and --access-key-secret are both set | -| `--oauth` | switch | no | Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a 30-day console session with automatic renewal | +| `--oauth` | switch | no | Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a console session with automatic renewal | | `--client-id ` | string | no | OAuth client ID; required for the first login outside pre-release | | `--scope ` | string | no | OAuth scope (default: openid /internal/bailian/cli) | | `--oauth-base-url ` | string | no | OAuth token service origin (production default: https://oauth.aliyun.com) | diff --git a/skills/bailian-cli/reference/index.md b/skills/bailian-cli/reference/index.md index 3a807203b..3d8918690 100644 --- a/skills/bailian-cli/reference/index.md +++ b/skills/bailian-cli/reference/index.md @@ -145,7 +145,7 @@ Use this index for the skill-scoped quick index and global flags. | `bl usage stats` | Console | Query model usage statistics | [usage.md](usage.md) | | `bl usage summary` | Console | Show a unified usage summary: free-tier quota and recent usage overview | [usage.md](usage.md) | | `bl usage token-plan` | Console | Show Token Plan quota usage | [usage.md](usage.md) | -| `bl workspace init` | AK/SK | Initialize Bailian workspace and activate postpaid services | [workspace.md](workspace.md) | +| `bl workspace init` | No Auth | Initialize Bailian workspace and activate postpaid services | [workspace.md](workspace.md) | | `bl workspace list` | Console | List all workspaces | [workspace.md](workspace.md) | ## By group diff --git a/skills/bailian-cli/reference/workspace.md b/skills/bailian-cli/reference/workspace.md index 21a192555..418e2ca43 100644 --- a/skills/bailian-cli/reference/workspace.md +++ b/skills/bailian-cli/reference/workspace.md @@ -9,34 +9,30 @@ Index: [index.md](index.md) | Command | Authentication | Description | | ------------------- | -------------- | ----------------------------------------------------------- | -| `bl workspace init` | AK/SK | Initialize Bailian workspace and activate postpaid services | +| `bl workspace init` | No Auth | Initialize Bailian workspace and activate postpaid services | | `bl workspace list` | Console | List all workspaces | ## Command details ### `bl workspace init` -| Field | Value | -| ------------------ | ----------------------------------------------------------- | -| **Name** | `workspace init` | -| **Description** | Initialize Bailian workspace and activate postpaid services | -| **Authentication** | AK/SK | -| **Usage** | `bl workspace init [flags]` | +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------ | +| **Name** | `workspace init` | +| **Description** | Initialize Bailian workspace and activate postpaid services | +| **Authentication** | No Auth | +| **Usage** | `bl workspace init --access-key-id --access-key-secret [--security-token ]` | #### Flags -| Flag | Type | Required | Description | -| --------------------------- | ------ | -------- | ---------------------------------------------------------------------- | -| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID) | -| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET) | -| `--security-token ` | string | no | Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN) | +| Flag | Type | Required | Description | +| ------------------------------ | ------ | -------- | ------------------------------------------- | +| `--access-key-id ` | string | no | Alibaba Cloud Access Key ID | +| `--access-key-secret ` | string | no | Alibaba Cloud Access Key Secret | +| `--security-token ` | string | no | Alibaba Cloud STS Security Token (optional) | #### Examples -```bash -bl workspace init -``` - ```bash bl workspace init --access-key-id LTAIxxxxx --access-key-secret xxxxx ``` From b96e57ca85e93286fa5b7b1dc9d2214b63fb7187 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Tue, 1 Dec 2026 22:28:31 +0800 Subject: [PATCH 11/13] fix(auth): harden OAuth session lifecycle and pre-release site routing - Route pre-release OpenAPI hosts by the OAuth profile site so international pre no longer resolves to domestic endpoints - Revoke the previous refresh token best-effort on relogin; logout stays local-first and warns instead of blocking when revoke fails offline - Scale session-lock wait budget with the operation timeout (two serial exchanges plus headroom, 30s floor) - Pre dry-run marks an explicit --console-gateway unverified when the env gateway is unset; configured gateways still must match the trusted value - Redact reflected refresh tokens in revoke failures across raw, percent-encoded and form-encoded forms - Cover the new contracts, lock-wait budget and the 16KB manual-callback boundary in tests --- packages/commands/src/commands/auth/aliyun.ts | 30 ++- packages/commands/src/commands/auth/login.ts | 6 +- .../commands/src/commands/token-plan/utils.ts | 9 + .../commands/src/commands/workspace/init.ts | 10 +- packages/commands/tests/auth-aliyun.test.ts | 15 ++ packages/commands/tests/e2e/auth.e2e.test.ts | 79 +++++++ .../commands/tests/token-plan-host.test.ts | 23 ++ packages/core/src/auth/aliyun-oauth.ts | 30 ++- packages/core/src/auth/openapi-provider.ts | 87 ++++--- packages/core/src/auth/store.ts | 105 ++++++--- packages/core/src/client/client.ts | 13 +- packages/core/src/config/control-plane.ts | 12 + packages/core/src/config/index.ts | 1 + packages/core/src/config/model-base-url.ts | 7 +- packages/core/src/config/store.ts | 3 +- packages/core/tests/aliyun-oauth.test.ts | 27 +++ packages/core/tests/model-base-url.test.ts | 7 + packages/core/tests/openapi-provider.test.ts | 215 ++++++++++++++++-- 18 files changed, 558 insertions(+), 121 deletions(-) create mode 100644 packages/commands/tests/token-plan-host.test.ts diff --git a/packages/commands/src/commands/auth/aliyun.ts b/packages/commands/src/commands/auth/aliyun.ts index ef0a799e3..89e8cafb8 100644 --- a/packages/commands/src/commands/auth/aliyun.ts +++ b/packages/commands/src/commands/auth/aliyun.ts @@ -192,13 +192,17 @@ function loginPlan( "--bailiancontrol-host", normalizeOpenApiHost, ); - trustedPreEndpoint( - options.consoleGateway, - saved?.console_gateway, - gateway, - "--console-gateway", - normalizeOrigin, - ); + // Without the env gateway (dry-run only), there is no trusted value to + // check against; the preview reports the explicit flag as unverified + // instead of rejecting every value against undefined. + if (gateway !== undefined) + trustedPreEndpoint( + options.consoleGateway, + saved?.console_gateway, + gateway, + "--console-gateway", + normalizeOrigin, + ); return { client_id: normalizedClientId, scope, @@ -657,6 +661,13 @@ export async function runAliyunOAuthLogin( const config = deps.settings.configName ?? "default"; if (dryRun) { const missingClientId = missing.includes("--client-id"); + const unverifiedGateway = !!options.consoleGateway && !plan.console_gateway; + const unverifiedNote = unverifiedGateway + ? localize(deps, { + "en-US": " Explicit --console-gateway is unverified without BAILIAN_PRE_CONSOLE_GATEWAY.", + "zh-CN": "缺少 BAILIAN_PRE_CONSOLE_GATEWAY,显式 --console-gateway 未校验。", + }) + : ""; const preEndpoints = preControlPlane ? `\n${localize(deps, { "en-US": "Pre-release endpoints", "zh-CN": "预发端点" })}: ${[ plan.authorization_url, @@ -677,11 +688,12 @@ export async function runAliyunOAuthLogin( ...(preControlPlane ? { environment: "pre" } : {}), plan, missing, + ...(unverifiedGateway ? { unverified: ["--console-gateway"] } : {}), }, { text: localize(deps, { - "en-US": `Would authorize Aliyun OAuth ${options.noBrowser ? "by pasting the callback URL without listening on a port" : "with a random loopback port"}, exchange STS, validate Console access and save the session. ${missingClientId ? "Missing required options" : "Missing endpoints"}: ${missing.join(", ") || "none"}.${preEndpoints}`, - "zh-CN": `将${options.noBrowser ? "通过粘贴回调 URL(不监听端口)" : "通过随机回环端口"}完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。${missingClientId ? "缺少必填选项" : "缺少端点"}:${missing.join("、") || "无"}。${preEndpoints}`, + "en-US": `Would authorize Aliyun OAuth ${options.noBrowser ? "by pasting the callback URL without listening on a port" : "with a random loopback port"}, exchange STS, validate Console access and save the session. ${missingClientId ? "Missing required options" : "Missing endpoints"}: ${missing.join(", ") || "none"}.${preEndpoints}${unverifiedNote}`, + "zh-CN": `将${options.noBrowser ? "通过粘贴回调 URL(不监听端口)" : "通过随机回环端口"}完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。${missingClientId ? "缺少必填选项" : "缺少端点"}:${missing.join("、") || "无"}。${preEndpoints}${unverifiedNote}`, }), }, ); diff --git a/packages/commands/src/commands/auth/login.ts b/packages/commands/src/commands/auth/login.ts index df761bb8d..3b38c5fd1 100644 --- a/packages/commands/src/commands/auth/login.ts +++ b/packages/commands/src/commands/auth/login.ts @@ -8,7 +8,7 @@ import { validateConsoleAccessToken, getModelProfilePreset, normalizeModelBaseUrl, - PRE_MODEL_STUDIO_HOST, + preOpenApiHostsForSite, requirePreConsoleGateway, requirePreConsoleOrigin, type Settings, @@ -44,10 +44,12 @@ function previewPreLogin( if (pre.consoleOrigin) origin = requirePreConsoleOrigin(pre, target); else missing.push("BAILIAN_PRE_CONSOLE_ORIGIN"); } + const openApiHost = + mode === "openapi" ? preOpenApiHostsForSite(target.site).modelstudioHost : undefined; const endpoints = { ...(origin ? { console_origin: origin } : {}), ...(gateway ? { console_gateway: gateway } : {}), - ...(mode === "openapi" ? { modelstudio_host: PRE_MODEL_STUDIO_HOST } : {}), + ...(openApiHost ? { modelstudio_host: openApiHost } : {}), }; const addresses = Object.values(endpoints).join(", "); return { diff --git a/packages/commands/src/commands/token-plan/utils.ts b/packages/commands/src/commands/token-plan/utils.ts index a912a2b42..a8ccedd28 100644 --- a/packages/commands/src/commands/token-plan/utils.ts +++ b/packages/commands/src/commands/token-plan/utils.ts @@ -1,6 +1,7 @@ import { formatCommand, REGIONS, + PRE_INTL_MODEL_STUDIO_HOST, buildAcsCanonicalQuery, type Client, type AcsQueryParams, @@ -52,6 +53,14 @@ function resolveRegion(baseUrl: string): Region { for (const [region, url] of Object.entries(REGIONS) as Array<[Region, string]>) { if (baseUrl === url || baseUrl.startsWith(`${url}/`)) return region; } + // OAuth login persists the ModelStudio host as the base URL; pre-release + // hosts are not REGIONS presets, so recognize the intl site explicitly. + const hostname = URL.canParse(baseUrl) ? new URL(baseUrl).hostname : baseUrl; + if ( + hostname === "modelstudio.ap-southeast-1.aliyuncs.com" || + (PRE_INTL_MODEL_STUDIO_HOST !== undefined && hostname === PRE_INTL_MODEL_STUDIO_HOST) + ) + return "intl"; return "cn"; } diff --git a/packages/commands/src/commands/workspace/init.ts b/packages/commands/src/commands/workspace/init.ts index 92f01870a..2dcb125d9 100644 --- a/packages/commands/src/commands/workspace/init.ts +++ b/packages/commands/src/commands/workspace/init.ts @@ -5,8 +5,7 @@ import { generateCLIAccessToken, callConsoleGateway, effectiveConsoleGatewayConfig, - PRE_BAILIAN_CONTROL_HOST, - PRE_MODEL_STUDIO_HOST, + preOpenApiHostsForSite, requirePreConsoleGateway, createBailianControlUser, listBailianControlWorkspaces, @@ -97,13 +96,16 @@ export default defineCommand({ const preGateway = pre?.consoleGateway ? requirePreConsoleGateway(pre, consoleTarget) : undefined; + const preHosts = preOpenApiHostsForSite(consoleTarget.site); ctx.output.result({ ...(pre ? { environment: "pre", endpoints: { - modelstudio_host: PRE_MODEL_STUDIO_HOST, - bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + ...(preHosts.modelstudioHost ? { modelstudio_host: preHosts.modelstudioHost } : {}), + ...(preHosts.bailiancontrolHost + ? { bailiancontrol_host: preHosts.bailiancontrolHost } + : {}), ...(preGateway ? { console_gateway: preGateway } : {}), }, missing: preGateway ? [] : ["BAILIAN_PRE_CONSOLE_GATEWAY"], diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index b5297aeb8..fee73a647 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -653,6 +653,21 @@ test("粘贴无效回调仅重试本次会话,不换票、不回显原文", as assertNoSecrets(probe, [callback.href]); }); +test("恰好低于 16KB 上限的无效行按无效回调重试,换行重置计数后仍可成功", async () => { + const input = new PassThrough(); + const probe = launch({ noBrowser: true }, { stdin: input }); + const callback = callbackUrl(await probe.authUrl); + input.write("x".repeat(16 * 1024 - 1) + "\n"); + expect(probe.stderr.join("")).toContain("Invalid OAuth callback address"); + expect(probe.stderr.join("")).not.toContain("too long"); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); + input.end(callback.href + "\n"); + expect(await probe.outcome).toBeUndefined(); + expect(new URLSearchParams(stringBody(requests[0]!.init.body)).get("code")).toBe(SECRETS.code); + assertNoSecrets(probe, [callback.href]); +}); + test.each(process.platform === "win32" ? ["Ctrl+C"] : ["Ctrl+C", "Ctrl+Z"])( "TTY 输入不回显且 %s 取消并清理 raw mode", async (key) => { diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index 7747bed2f..a6101509f 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -276,6 +276,85 @@ describe("e2e: auth", () => { expect(completeData.missing).toEqual([]); }); + test("国际预发:--open-api dry-run 预览按站点展示国际预发 OpenAPI host", async () => { + const result = await runCommandInProcess( + AUTH_ROUTES, + [ + "auth", + "login", + "--open-api", + "--access-key-id", + "fixture-ak", + "--access-key-secret", + "fixture-sk", + "--console-site", + "international", + "--dry-run", + "--output", + "json", + ], + { BAILIAN_PRE: "1" }, + ); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + environment: string; + endpoints: { modelstudio_host?: string }; + missing: string[]; + }>(result.stdout); + expect(data.environment).toBe("pre"); + expect(data.endpoints.modelstudio_host).toBe("modelstudio-pre.ap-southeast-1.aliyuncs.com"); + expect(data.missing).toEqual(["BAILIAN_PRE_CONSOLE_GATEWAY"]); + }); + + test("预发 dry-run 缺网关时显式 --console-gateway 标未校验而非拒绝", async () => { + const result = await runCommandInProcess( + AUTH_ROUTES, + [ + "auth", + "login", + "--oauth", + "--console-gateway", + "https://pre-bailian-cs.console.aliyun.com", + "--dry-run", + "--output", + "json", + ], + { BAILIAN_PRE: "1" }, + ); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + plan: { console_gateway?: string }; + missing: string[]; + unverified?: string[]; + }>(result.stdout); + expect(data.plan.console_gateway).toBeUndefined(); + expect(data.missing).toEqual(["BAILIAN_PRE_CONSOLE_GATEWAY"]); + expect(data.unverified).toEqual(["--console-gateway"]); + }); + + test("预发 dry-run 配齐网关后显式 --console-gateway 仍须匹配可信值", async () => { + const result = await runCommandInProcess( + AUTH_ROUTES, + [ + "auth", + "login", + "--oauth", + "--console-gateway", + "https://evil.example.com", + "--dry-run", + "--output", + "json", + ], + { + BAILIAN_PRE: "1", + BAILIAN_PRE_CONSOLE_GATEWAY: "https://pre-bailian-cs.console.aliyun.com", + }, + ); + expect(result.exitCode).toBe(2); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("--console-gateway"); + }); + test("auth login 模式专属参数不能脱离对应模式", async () => { const openApiFlagOnly = await runCommandE2e(AUTH_ROUTES, [ "auth", diff --git a/packages/commands/tests/token-plan-host.test.ts b/packages/commands/tests/token-plan-host.test.ts new file mode 100644 index 000000000..56d827817 --- /dev/null +++ b/packages/commands/tests/token-plan-host.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "vite-plus/test"; +import { PRE_INTL_MODEL_STUDIO_HOST, PRE_MODEL_STUDIO_HOST, type Client } from "bailian-cli-core"; +import { prepareTokenPlanRequest } from "../src/commands/token-plan/utils.ts"; + +function hostForBaseUrl(baseUrl: string): string { + const client = { + baseUrl, + resolveOpenApiHost: (host: string) => host, + } as unknown as Client; + return prepareTokenPlanRequest(client, "/readonly", {}).host; +} + +describe("token-plan ModelStudio host derivation", () => { + test.each([ + ["https://dashscope.aliyuncs.com", "modelstudio.cn-beijing.aliyuncs.com"], + ["https://dashscope-intl.aliyuncs.com", "modelstudio.ap-southeast-1.aliyuncs.com"], + ["https://modelstudio.ap-southeast-1.aliyuncs.com", "modelstudio.ap-southeast-1.aliyuncs.com"], + [`https://${PRE_MODEL_STUDIO_HOST}`, "modelstudio.cn-beijing.aliyuncs.com"], + [`https://${PRE_INTL_MODEL_STUDIO_HOST}`, "modelstudio.ap-southeast-1.aliyuncs.com"], + ])("derives the site host from %s", (baseUrl, expectedHost) => { + expect(hostForBaseUrl(baseUrl)).toBe(expectedHost); + }); +}); diff --git a/packages/core/src/auth/aliyun-oauth.ts b/packages/core/src/auth/aliyun-oauth.ts index 5f1930ae5..cbc612b83 100644 --- a/packages/core/src/auth/aliyun-oauth.ts +++ b/packages/core/src/auth/aliyun-oauth.ts @@ -16,6 +16,15 @@ export interface AliyunOAuthDeps extends Pick { recoveryHint?: string; } +/** + * A session-lock holder may run the refresh chain (two sequential exchanges, + * each bounded by the operation timeout) under the lock; waiters must outlast + * it instead of failing at the default 30s. + */ +export function oauthLockTimeout(timeoutSeconds: number | undefined): number { + return Math.max(30_000, (timeoutSeconds ?? 30) * 2000 + 5_000); +} + export function createOAuthProofKey(): { state: string; verifier: string; challenge: string } { const verifier = randomBytes(32).toString("base64url"); return { @@ -60,6 +69,18 @@ export function parseAliyunCallback(url: URL, state: string): string { return codes[0]; } +/** Redact raw, percent-encoded and form-encoded secret forms from service errors. */ +function redactSecrets(message: string, secrets: string[]): string { + let redacted = message; + for (const secret of secrets.flatMap((value) => [ + value, + encodeURIComponent(value), + new URLSearchParams({ value }).toString().slice(6), + ])) + if (secret) redacted = redacted.replaceAll(secret, "[REDACTED]"); + return redacted; +} + async function postOAuth( profile: Pick, path: string, @@ -96,12 +117,7 @@ async function postOAuth( const errorMessage = data.error_description ?? data.Message ?? data.message ?? data.error ?? response.statusText; let message = typeof errorMessage === "string" ? errorMessage : JSON.stringify(errorMessage)!; - for (const secret of secrets.flatMap((value) => [ - value, - encodeURIComponent(value), - new URLSearchParams({ value }).toString().slice(6), - ])) - if (secret) message = message.replaceAll(secret, "[REDACTED]"); + message = redactSecrets(message, secrets); const apiCode = data.error ?? data.Code; const requestId = data.requestId ?? data.RequestId ?? response.headers.get("x-request-id"); throw new BailianError(message, ExitCode.GENERAL, undefined, { @@ -295,7 +311,7 @@ export async function revokeAliyunTokens( const apiCode = data.error ?? data.Code; const requestId = data.requestId ?? data.RequestId ?? response.headers.get("x-request-id"); throw new BailianError( - message.replaceAll(refreshToken, "[REDACTED]") || `HTTP ${response.status}`, + redactSecrets(message, [refreshToken]) || `HTTP ${response.status}`, ExitCode.GENERAL, undefined, { diff --git a/packages/core/src/auth/openapi-provider.ts b/packages/core/src/auth/openapi-provider.ts index f3431ef03..bbabffa7c 100644 --- a/packages/core/src/auth/openapi-provider.ts +++ b/packages/core/src/auth/openapi-provider.ts @@ -12,7 +12,12 @@ import { UsageError, BailianError } from "../errors/base.ts"; import { withFileLock } from "../utils/file-lock.ts"; import { resolveOpenApi } from "./resolver.ts"; import { createOAuthSecretStore, type OAuthSecretStore } from "./secure-store.ts"; -import { exchangeAliyunSts, refreshAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; +import { + exchangeAliyunSts, + oauthLockTimeout, + refreshAliyunTokens, + type AliyunOAuthDeps, +} from "./aliyun-oauth.ts"; import { profileSite } from "./aliyun-config.ts"; import type { AliyunOAuthProfile, @@ -318,21 +323,24 @@ export function createOpenApiCredentialProvider( resolveHost(host, credential, purpose = "openapi") { const profile = selectedOAuth(currentSources(), purpose); assertOAuthRouteBinding(profile, credential); - if (pre) return resolvePreOpenApiHost(host); - if (!profile || (credential && credential.method !== "aliyun-oauth")) return host; - if ( - /^modelstudio(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host) || - host === profile.modelstudio_host - ) - return profile.modelstudio_host; - if (/^bailiancontrol(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host)) { - if (!profile.bailiancontrol_host) - throw new UsageError( - "Configure --bailiancontrol-host when signing in before calling BailianControl with this OAuth profile. / 使用此 OAuth 配置调用 BailianControl 前,请在登录时配置 --bailiancontrol-host。", - ); - return profile.bailiancontrol_host; + let mapped = host; + if (profile && (!credential || credential.method === "aliyun-oauth")) { + if ( + /^modelstudio(?:-pre)?(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host) || + host === profile.modelstudio_host + ) + mapped = profile.modelstudio_host; + else if (/^bailiancontrol(?:-pre)?(?:\.[a-z0-9-]+)?\.aliyuncs\.com$/u.test(host)) { + if (!profile.bailiancontrol_host) + throw new UsageError( + "Configure --bailiancontrol-host when signing in before calling BailianControl with this OAuth profile. / 使用此 OAuth 配置调用 BailianControl 前,请在登录时配置 --bailiancontrol-host。", + ); + mapped = profile.bailiancontrol_host; + } } - return host; + // The profile's site decides the pre-release identity; callers may pass a + // default-site guess (e.g. token-plan derives hosts from the base URL). + return pre ? resolvePreOpenApiHost(mapped) : mapped; }, async getCredential(purpose = "openapi") { const current = currentSources(); @@ -410,6 +418,7 @@ export function createOpenApiCredentialProvider( assertReference(profile, purpose); return credentialFrom(profile, session); }, + oauthLockTimeout(deps.timeout), ); pending.set(profile.session_ref, exchange); try { @@ -460,29 +469,33 @@ export function createOpenApiCredentialProvider( ) return; validateTarget(profile, credential); - await withFileLock(oauthSessionLockPath(directory, profile.session_ref), async () => { - const current = currentSources().file.aliyun_oauth; - if ( - !current || - current.session_ref !== credential.sessionRef || - !current.console_enabled || - credential.configurationFingerprint !== oauthConfigurationFingerprint(current) - ) - return; - const session = parseOAuthSession(await getStore().read(profile.session_ref)); - assertOAuthConfiguration(profile, session); - const key = consoleCredentialKey({ ...credential, gateway: profile.console_gateway }); - await save(profile, { - ...session, - consoleTokens: { - ...session.consoleTokens, - [key]: { - token: credential.token, - ...(credential.expiresAt !== undefined ? { expiresAt: credential.expiresAt } : {}), + await withFileLock( + oauthSessionLockPath(directory, profile.session_ref), + async () => { + const current = currentSources().file.aliyun_oauth; + if ( + !current || + current.session_ref !== credential.sessionRef || + !current.console_enabled || + credential.configurationFingerprint !== oauthConfigurationFingerprint(current) + ) + return; + const session = parseOAuthSession(await getStore().read(profile.session_ref)); + assertOAuthConfiguration(profile, session); + const key = consoleCredentialKey({ ...credential, gateway: profile.console_gateway }); + await save(profile, { + ...session, + consoleTokens: { + ...session.consoleTokens, + [key]: { + token: credential.token, + ...(credential.expiresAt !== undefined ? { expiresAt: credential.expiresAt } : {}), + }, }, - }, - }); - }); + }); + }, + oauthLockTimeout(deps.timeout), + ); }, }; } diff --git a/packages/core/src/auth/store.ts b/packages/core/src/auth/store.ts index 2389dabe7..16ba0e9c5 100644 --- a/packages/core/src/auth/store.ts +++ b/packages/core/src/auth/store.ts @@ -11,7 +11,7 @@ import { oauthConfigurationFingerprint, assertOAuthConfiguration, } from "./openapi-provider.ts"; -import { revokeAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; +import { oauthLockTimeout, revokeAliyunTokens, type AliyunOAuthDeps } from "./aliyun-oauth.ts"; import { profileSite, parseAliyunOAuthProfile } from "./aliyun-config.ts"; import type { AliyunOAuthProfile, AliyunOAuthSession } from "./aliyun-types.ts"; import { CredentialError } from "../errors/credential.ts"; @@ -213,10 +213,39 @@ export function makeAuthStore( } }); if (previous) { + const previousProfile = previous; const referenceToRemove = previous.session_ref; try { - await withFileLock(oauthSessionLockPath(directory, referenceToRemove), () => - getSecretStore().remove(referenceToRemove), + await withFileLock( + oauthSessionLockPath(directory, referenceToRemove), + async () => { + // The old refresh token stays valid on the server for its full + // lifetime unless revoked; failure here must not block the new login. + if (oauthDeps) { + try { + const raw = await getSecretStore().read(referenceToRemove); + const previousSession = raw ? parseOAuthSession(raw) : undefined; + if (previousSession?.refreshToken) { + assertOAuthConfiguration(previousProfile, previousSession); + await revokeAliyunTokens( + previousProfile, + previousSession.refreshToken, + oauthDeps, + ); + } + } catch { + oauthDeps.warning?.({ + message: { + "en-US": + "Signed in, but the previous refresh token could not be revoked; it remains valid on the server until it expires.", + "zh-CN": "登录成功,但未能撤销之前的刷新令牌;它在服务端到期前仍然有效。", + }, + }); + } + } + await getSecretStore().remove(referenceToRemove); + }, + oauthLockTimeout(oauthDeps?.timeout), ); } catch { oauthDeps?.warning?.({ @@ -284,35 +313,51 @@ export function makeAuthStore( return clearConfig(); } const sessionReference = validProfile.session_ref; - return withFileLock(oauthSessionLockPath(directory, sessionReference), async () => { - const current = readRecoverableConfig().aliyun_oauth; - if (current?.session_ref !== sessionReference) throw changedSession(); - const currentValid = strictOAuthProfile(current); - if (pre && currentValid) validatePreAliyunProfile(currentValid); - const raw = await getSecretStore().read(sessionReference); - if (removeOAuth) { - if (raw && currentValid) { - const session = parseOAuthSession(raw); - assertOAuthConfiguration(currentValid, session); - if (session.refreshToken) { - if (!oauthDeps) - throw new CredentialError( - "missing-aliyun-session", - "OAuth logout requires OAuth transport dependencies. / OAuth 退出需要 OAuth 传输配置。", - ); - await revokeAliyunTokens(currentValid, session.refreshToken, oauthDeps); + return withFileLock( + oauthSessionLockPath(directory, sessionReference), + async () => { + const current = readRecoverableConfig().aliyun_oauth; + if (current?.session_ref !== sessionReference) throw changedSession(); + const currentValid = strictOAuthProfile(current); + if (pre && currentValid) validatePreAliyunProfile(currentValid); + const raw = await getSecretStore().read(sessionReference); + if (removeOAuth) { + if (raw && currentValid) { + const session = parseOAuthSession(raw); + assertOAuthConfiguration(currentValid, session); + if (session.refreshToken) { + if (!oauthDeps) + throw new CredentialError( + "missing-aliyun-session", + "OAuth logout requires OAuth transport dependencies. / OAuth 退出需要 OAuth 传输配置。", + ); + // Local sign-out must work offline; a failed revoke only leaves the + // server-side token alive until it expires, so warn instead of blocking. + try { + await revokeAliyunTokens(currentValid, session.refreshToken, oauthDeps); + } catch { + oauthDeps.warning?.({ + message: { + "en-US": + "Signed out locally, but the refresh token could not be revoked; it remains valid on the server until it expires.", + "zh-CN": "已在本地退出,但未能撤销刷新令牌;它在服务端到期前仍然有效。", + }, + }); + } + } } + await getSecretStore().remove(sessionReference); + } else if (raw) { + const session = parseOAuthSession(raw); + await getSecretStore().write( + sessionReference, + JSON.stringify({ ...session, consoleTokens: {} }), + ); } - await getSecretStore().remove(sessionReference); - } else if (raw) { - const session = parseOAuthSession(raw); - await getSecretStore().write( - sessionReference, - JSON.stringify({ ...session, consoleTokens: {} }), - ); - } - return clearConfig(); - }); + return clearConfig(); + }, + oauthLockTimeout(oauthDeps?.timeout), + ); }, get path() { return configurationPath; diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index c20973a99..90f273a6e 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -352,15 +352,10 @@ export class Client { const { settings, openApiProvider } = this.deps; if (settings.preControlPlane) { validatePreConsoleScope({ region: settings.consoleRegion, site: settings.consoleSite }); - const expected = resolvePreOpenApiHost(host); - const resolved = openApiProvider?.resolveHost(host, credential) ?? expected; - if (resolvePreOpenApiHost(resolved) !== expected) { - throw new CredentialError( - "changed-openapi-identity", - "The OpenAPI endpoint does not match the pre-release route. / OpenAPI 端点与预发路由不匹配。", - ); - } - return expected; + // The provider maps the host through the OAuth profile's site first; the + // input host may be a default-site guess, so it cannot anchor the identity. + const resolved = openApiProvider?.resolveHost(host, credential) ?? host; + return resolvePreOpenApiHost(resolved); } return openApiProvider?.resolveHost(host, credential) ?? host; } diff --git a/packages/core/src/config/control-plane.ts b/packages/core/src/config/control-plane.ts index aa1ff133c..0d6d7d45d 100644 --- a/packages/core/src/config/control-plane.ts +++ b/packages/core/src/config/control-plane.ts @@ -175,6 +175,18 @@ export function requirePreConsoleGateway( return requirePreEndpoint(pre, target, "consoleGateway"); } +/** Site-aware pre-release OpenAPI hosts for previews; undefined means unconfirmed. */ +export function preOpenApiHostsForSite(site: string | undefined): { + modelstudioHost: string | undefined; + bailiancontrolHost: string | undefined; +} { + const group = site === "international" ? PRE_INTL_GROUP : PRE_DOMESTIC_GROUP; + return { + modelstudioHost: group.modelStudioHost, + bailiancontrolHost: group.bailiancontrolHost, + }; +} + export function resolvePreOpenApiHost(host: string): string { switch (host) { case "modelstudio.aliyuncs.com": diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.ts index 8ab7c12e1..c0b8c6cb6 100644 --- a/packages/core/src/config/index.ts +++ b/packages/core/src/config/index.ts @@ -68,6 +68,7 @@ export { requirePreConsoleOrigin, resolvePreControlPlane, resolvePreOpenApiHost, + preOpenApiHostsForSite, validatePreConsoleScope, validatePreConsoleRegion, intlPreEndpointsConfirmed, diff --git a/packages/core/src/config/model-base-url.ts b/packages/core/src/config/model-base-url.ts index 9d2a1d2b6..f6e1dbab1 100644 --- a/packages/core/src/config/model-base-url.ts +++ b/packages/core/src/config/model-base-url.ts @@ -6,7 +6,8 @@ import { ExitCode } from "../errors/codes.ts"; * CLI endpoints append their own API paths, so user-provided paths, query * parameters, and fragments must not remain in the stored or resolved base URL. */ -export function normalizeModelBaseUrl(input: string): string { +export function normalizeModelBaseUrl(input: unknown): string { + if (typeof input !== "string") throw invalidModelBaseUrl(input); const trimmed = input.trim(); let parsed: URL; try { @@ -22,9 +23,9 @@ export function normalizeModelBaseUrl(input: string): string { return parsed.origin; } -function invalidModelBaseUrl(input: string): BailianError { +function invalidModelBaseUrl(input: unknown): BailianError { return new BailianError( - `Invalid model base URL "${input}".`, + `Invalid model base URL "${String(input)}".`, ExitCode.USAGE, "Use an absolute http(s) URL.", ); diff --git a/packages/core/src/config/store.ts b/packages/core/src/config/store.ts index 53eb7319b..ae9914a52 100644 --- a/packages/core/src/config/store.ts +++ b/packages/core/src/config/store.ts @@ -41,8 +41,7 @@ export function makeConfigStore( const existing = { ...current } as Record; for (const [key, value] of Object.entries(patch)) { if (value === undefined) delete existing[key]; - else - existing[key] = key === "base_url" ? normalizeModelBaseUrl(value as string) : value; + else existing[key] = key === "base_url" ? normalizeModelBaseUrl(value) : value; } return existing as ConfigFile; }, diff --git a/packages/core/tests/aliyun-oauth.test.ts b/packages/core/tests/aliyun-oauth.test.ts index 6c35cf363..17a297308 100644 --- a/packages/core/tests/aliyun-oauth.test.ts +++ b/packages/core/tests/aliyun-oauth.test.ts @@ -13,6 +13,7 @@ import { createOAuthProofKey, exchangeAliyunCode, exchangeAliyunSts, + oauthLockTimeout, parseAliyunCallback, refreshAliyunTokens, revokeAliyunTokens, @@ -297,6 +298,13 @@ describe("Aliyun OAuth token and STS wire protocol", () => { }); expectNoSecrets(); }); + + test("session-lock wait budget covers two serial exchanges and keeps a 30s floor", () => { + expect(oauthLockTimeout(300)).toBe(605_000); + expect(oauthLockTimeout(30)).toBe(65_000); + expect(oauthLockTimeout(5)).toBe(30_000); + expect(oauthLockTimeout(undefined)).toBe(65_000); + }); }); describe("token, scope and expiry validation", () => { @@ -526,4 +534,23 @@ describe("OAuth failures preserve API context without credentials", () => { }); expectNoSecrets(error); }); + + test("revoke failure redacts percent-encoded and form-encoded RT reflections", async () => { + const encodedRefresh = "fixture-refresh+with&encoding /"; + const percentEncoded = encodeURIComponent(encodedRefresh); + const formEncoded = new URLSearchParams({ value: encodedRefresh }).toString().slice(6); + expect(new Set([encodedRefresh, percentEncoded, formEncoded]).size).toBe(3); + transport.mockResolvedValue( + response( + { + error: "temporarily_unavailable", + error_description: `Cannot revoke ${encodedRefresh} | ${percentEncoded} | ${formEncoded}`, + }, + 503, + ), + ); + const error = await caughtError(revokeAliyunTokens(PROFILE, encodedRefresh, deps)); + expect(error.message).toBe("Cannot revoke [REDACTED] | [REDACTED] | [REDACTED]"); + expect(JSON.stringify(error.toJSON())).not.toContain(encodedRefresh); + }); }); diff --git a/packages/core/tests/model-base-url.test.ts b/packages/core/tests/model-base-url.test.ts index 3ee247449..96a1f0e18 100644 --- a/packages/core/tests/model-base-url.test.ts +++ b/packages/core/tests/model-base-url.test.ts @@ -35,3 +35,10 @@ test("normalizeModelBaseUrl rejects non-http and malformed URLs", () => { expect(() => normalizeModelBaseUrl("not a url")).toThrow(BailianError); expect(() => normalizeModelBaseUrl("ftp://example.com/path")).toThrow(/Invalid model base URL/); }); + +test("normalizeModelBaseUrl rejects non-string values as usage errors", () => { + for (const value of [undefined, null, 42, {}, ["https://example.com"]]) { + expect(() => normalizeModelBaseUrl(value)).toThrow(BailianError); + expect(() => normalizeModelBaseUrl(value)).toThrow(/Invalid model base URL/); + } +}); diff --git a/packages/core/tests/openapi-provider.test.ts b/packages/core/tests/openapi-provider.test.ts index 6ab289ad9..0249a1d1b 100644 --- a/packages/core/tests/openapi-provider.test.ts +++ b/packages/core/tests/openapi-provider.test.ts @@ -1,7 +1,7 @@ import { spawn, type ChildProcess } from "node:child_process"; import files, { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { syncBuiltinESMExports } from "node:module"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, @@ -19,6 +19,7 @@ import { consoleCredentialKey, createOpenApiCredentialProvider, oauthConfigurationFingerprint, + oauthSessionLockPath, } from "../src/auth/openapi-provider.ts"; import type { OAuthSecretStore } from "../src/auth/secure-store.ts"; import { makeAuthStore } from "../src/auth/store.ts"; @@ -26,7 +27,17 @@ import type { ConsoleCredential } from "../src/auth/types.ts"; import { Client } from "../src/client/client.ts"; import { httpTransport } from "../src/client/transport.ts"; import { anonymousConsoleCall } from "../src/console/gateway.ts"; -import { PRE_MODEL_STUDIO_HOST, resolvePreControlPlane } from "../src/config/control-plane.ts"; +import { + PRE_ALIYUN_AUTHORIZATION_URL, + PRE_ALIYUN_OAUTH_BASE_URL, + PRE_BAILIAN_CONTROL_HOST, + PRE_INTL_ALIYUN_AUTHORIZATION_URL, + PRE_INTL_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_BAILIAN_CONTROL_HOST, + PRE_INTL_MODEL_STUDIO_HOST, + PRE_MODEL_STUDIO_HOST, + resolvePreControlPlane, +} from "../src/config/control-plane.ts"; import { getConfigPath } from "../src/config/paths.ts"; import { activateConfigProfile, @@ -39,7 +50,7 @@ import { type ResolutionSources, } from "../src/config/loader.ts"; import type { ConfigFile } from "../src/config/schema.ts"; -import { BailianError, UsageError } from "../src/errors/base.ts"; +import { UsageError } from "../src/errors/base.ts"; import { CredentialError } from "../src/errors/credential.ts"; import { withFileLock } from "../src/utils/file-lock.ts"; import { enterIsolatedHome, type IsolatedHomeHandle } from "./helpers/isolation.ts"; @@ -313,6 +324,95 @@ describe("pre-release control-plane isolation", () => { }); }); +describe("pre-release site-aware OpenAPI routing", () => { + const intlProfile = () => + profile({ + authorization_url: PRE_INTL_ALIYUN_AUTHORIZATION_URL!, + oauth_base_url: PRE_INTL_ALIYUN_OAUTH_BASE_URL!, + modelstudio_host: PRE_INTL_MODEL_STUDIO_HOST!, + bailiancontrol_host: PRE_INTL_BAILIAN_CONTROL_HOST!, + console_gateway: "https://pre-bailian-singapore-cs.alibabacloud.com", + console_region: "ap-southeast-1", + console_site: "international", + }); + const domesticProfile = () => + profile({ + authorization_url: PRE_ALIYUN_AUTHORIZATION_URL, + oauth_base_url: PRE_ALIYUN_OAUTH_BASE_URL, + modelstudio_host: PRE_MODEL_STUDIO_HOST, + bailiancontrol_host: PRE_BAILIAN_CONTROL_HOST, + console_gateway: "https://pre-bailian-cs.console.aliyun.com", + console_region: "cn-beijing", + }); + + async function setupPreOAuth(profileValue: AliyunOAuthProfile) { + const sources = buildSources({}, undefined, resolvePreControlPlane({ BAILIAN_PRE: "1" })!); + const fake = memoryStore(); + const storage = { store: fake.store, directory: dirname(sources.configPath!) }; + const auth = makeAuthStore(sources, deps, storage); + await auth.loginAliyun(profileValue, session({ sts: sts() })); + const liveSources: ResolutionSources = { + ...sources, + file: readConfigFile(sources.configName, sources.configPath), + }; + return { + ...fake, + sources: liveSources, + auth, + provider: createOpenApiCredentialProvider(liveSources, deps, storage), + }; + } + + test("intl OAuth profile maps default-site guesses to the intl pre hosts", async () => { + const instance = await setupPreOAuth(intlProfile()); + expect(instance.provider.resolveHost("modelstudio.cn-beijing.aliyuncs.com")).toBe( + PRE_INTL_MODEL_STUDIO_HOST, + ); + expect(instance.provider.resolveHost("modelstudio.aliyuncs.com")).toBe( + PRE_INTL_MODEL_STUDIO_HOST, + ); + expect(instance.provider.resolveHost(PRE_MODEL_STUDIO_HOST)).toBe(PRE_INTL_MODEL_STUDIO_HOST); + expect(instance.provider.resolveHost("bailiancontrol.cn-beijing.aliyuncs.com")).toBe( + PRE_INTL_BAILIAN_CONTROL_HOST, + ); + expect(transport).not.toHaveBeenCalled(); + }); + + test("signs intl pre OpenAPI requests against the intl host end to end", async () => { + const instance = await setupPreOAuth(intlProfile()); + const client = new Client({ + identity: deps.identity, + baseUrl: `https://${PRE_INTL_MODEL_STUDIO_HOST}`, + settings: buildSettings(instance.sources), + openApiProvider: instance.provider, + }); + transport.mockResolvedValueOnce(json({ Success: true })); + await expect( + client.openApiJson({ + host: "modelstudio.cn-beijing.aliyuncs.com", + path: "/readonly", + action: "ListFixture", + version: "2026-01-01", + method: "GET", + }), + ).resolves.toEqual({ Success: true }); + const [endpoint, init] = transport.mock.calls[0]!; + expect(endpoint).toBe(`https://${PRE_INTL_MODEL_STUDIO_HOST}/readonly`); + expect(new Headers(init?.headers).get("authorization")).toContain("Credential=fixture-sts-id"); + }); + + test("domestic OAuth profile keeps domestic pre hosts even for intl guesses", async () => { + const instance = await setupPreOAuth(domesticProfile()); + expect(instance.provider.resolveHost("modelstudio.ap-southeast-1.aliyuncs.com")).toBe( + PRE_MODEL_STUDIO_HOST, + ); + expect(instance.provider.resolveHost("bailiancontrol.ap-southeast-1.aliyuncs.com")).toBe( + PRE_BAILIAN_CONTROL_HOST, + ); + expect(transport).not.toHaveBeenCalled(); + }); +}); + describe("OpenAPI credential source selection and pure preflight", () => { const env = { BAILIAN_ACCESS_KEY_ID: " fixture-bailian-id ", @@ -1113,11 +1213,16 @@ describe("Console retry identity pinning", () => { }); return expired(); }); + // Relogin best-effort revokes the previous RT as a second transport call. + const revokeCalls = replacement === "new OAuth session" ? 1 : 0; + if (revokeCalls) transport.mockResolvedValueOnce(new Response(null, { status: 204 })); await expect(instance.client.console("fixture.readOnly", {})).rejects.toBeInstanceOf( CredentialError, ); - expect(transport).toHaveBeenCalledTimes(1); - expect(instance.store.read.mock.calls).toEqual([[REFERENCE]]); + expect(transport).toHaveBeenCalledTimes(1 + revokeCalls); + expect(instance.store.read.mock.calls).toEqual( + Array.from({ length: 1 + revokeCalls }, () => [REFERENCE]), + ); }, ); @@ -1145,6 +1250,11 @@ describe("Console retry identity pinning", () => { firstStarted.resolve(); return firstResponse.promise; }) + .mockImplementationOnce(async (input) => + endpointUrl(input).endsWith("/v1/revoke") + ? new Response(null, { status: 204 }) + : json(success), + ) .mockResolvedValueOnce(json(success)); const pending = expect(instance.client.console("fixture.firstRead", {})).rejects.toMatchObject({ reason: "changed-openapi-identity", @@ -1163,7 +1273,7 @@ describe("Console retry identity pinning", () => { firstResponse.resolve(expired()); await pending; } - expect(transport).toHaveBeenCalledTimes(2); + expect(transport).toHaveBeenCalledTimes(3); }); test("exchanges once and replays normally within the same OAuth session", async () => { @@ -1217,6 +1327,44 @@ describe("credential and configuration lock recovery", () => { await expect(readdir(path)).rejects.toMatchObject({ code: "ENOENT" }); }, ); + + test("a refresh waiter outlasts a slow lock holder when the operation timeout is large", async () => { + vi.useFakeTimers(); + try { + deps.timeout = 300; + const instance = await setup({ oauthSession: session() }); + transport.mockResolvedValue(stsResponse()); + const entered = deferred(); + const release = deferred(); + const holder = withFileLock( + oauthSessionLockPath(isolation.configDir, REFERENCE), + async () => { + entered.resolve(); + await release.promise; + }, + ); + await entered.promise; + let settled = false; + const outcome = instance.provider.getCredential().then( + (credential) => { + settled = true; + return credential; + }, + (error: unknown) => { + settled = true; + throw error; + }, + ); + await vi.advanceTimersByTimeAsync(31_000); + expect(settled).toBe(false); + release.resolve(); + await vi.advanceTimersByTimeAsync(1_000); + expect((await outcome).accessKeyId).toBe(sts().accessKeyId); + await holder; + } finally { + vi.useRealTimers(); + } + }); }); describe("Profile references, login and domain-specific logout", () => { @@ -1317,9 +1465,10 @@ describe("Profile references, login and domain-specific logout", () => { expect(await instance.auth.logout("openapi")).toBe(true); }); - test("relogin uses a new reference and invalidates credentials held by the old provider", async () => { + test("relogin revokes the previous refresh token, uses a new reference and invalidates old credentials", async () => { const instance = await setup({ oauthSession: session({ sts: sts() }) }); const previous = await instance.provider.getCredential(); + transport.mockResolvedValue(new Response(null, { status: 204 })); await instance.auth.loginAliyun( profile(), session({ @@ -1328,6 +1477,9 @@ describe("Profile references, login and domain-specific logout", () => { sts: { ...sts(), accessKeyId: "fixture-new-sts-id" }, }), ); + expect(transport).toHaveBeenCalledTimes(1); + expect(new URL(endpointUrl(transport.mock.calls[0]![0])).pathname).toBe("/v1/revoke"); + expect(formBody(transport.mock.calls[0]![1]).get("token")).toBe(REFRESH); const nextReference = readConfigFile().aliyun_oauth!.session_ref; expect(nextReference).not.toBe(REFERENCE); expect(instance.values.has(REFERENCE)).toBe(false); @@ -1337,7 +1489,34 @@ describe("Profile references, login and domain-specific logout", () => { const next = await instance.provider.getCredential(); expect(next.sessionRef).toBe(nextReference); expect(next.accessKeyId).toBe("fixture-new-sts-id"); - expect(transport).not.toHaveBeenCalled(); + expect(transport).toHaveBeenCalledTimes(1); + }); + + test("relogin warns when the previous refresh token cannot be revoked and still removes the old session", async () => { + const warning = vi.fn(); + deps.warning = warning; + const instance = await setup({ oauthSession: session({ sts: sts() }) }); + transport.mockResolvedValue( + json({ error: "temporarily_unavailable", error_description: "fixture-revoke-error" }, 503), + ); + await instance.auth.loginAliyun( + profile(), + session({ + accessToken: ROTATED_ACCESS, + refreshToken: ROTATED_REFRESH, + sts: { ...sts(), accessKeyId: "fixture-new-sts-id" }, + }), + ); + expect(warning).toHaveBeenCalledTimes(1); + expect(warning.mock.calls[0]![0].message["en-US"]).toContain("could not be revoked"); + expect(warning.mock.calls[0]![0].message["zh-CN"]).toContain("未能撤销之前的刷新令牌"); + expect(transport).toHaveBeenCalledTimes(1); + expect(new URL(endpointUrl(transport.mock.calls[0]![0])).pathname).toBe("/v1/revoke"); + expect(instance.values.has(REFERENCE)).toBe(false); + const nextReference = readConfigFile().aliyun_oauth!.session_ref; + expect(nextReference).not.toBe(REFERENCE); + expect(instance.values.has(nextReference)).toBe(true); + expect((await instance.provider.getCredential()).accessKeyId).toBe("fixture-new-sts-id"); }); test("provider is pinned to its selected profile even when active profile changes", async () => { @@ -1382,23 +1561,21 @@ describe("Profile references, login and domain-specific logout", () => { expect(readConfigFile().api_key).toBe(MODEL_KEY); }); - test("failed revoke preserves retryable local state; successful OAuth logout preserves model API key", async () => { + test("failed revoke still signs out locally with a warning; OAuth logout preserves model API key", async () => { + const warning = vi.fn(); + deps.warning = warning; const instance = await setup({ file: { aliyun_oauth: profile(), api_key: MODEL_KEY, base_url: "https://model.example.test" }, oauthSession: session({ sts: sts() }), }); const credential = await instance.provider.getCredential(); - const before = await configText(); - const secretBefore = instance.values.get(REFERENCE); transport.mockResolvedValue( json({ error: "temporarily_unavailable", error_description: "fixture-revoke-error" }, 503), ); - await expect(instance.auth.logout("aliyun")).rejects.toBeInstanceOf(BailianError); - expect(await configText()).toBe(before); - expect(instance.values.get(REFERENCE)).toBe(secretBefore); - expect(instance.store.remove).not.toHaveBeenCalled(); - transport.mockResolvedValue(new Response(null, { status: 204 })); expect(await instance.auth.logout("aliyun")).toBe(true); + expect(warning).toHaveBeenCalledTimes(1); + expect(warning.mock.calls[0]![0].message["en-US"]).toContain("could not be revoked"); + expect(warning.mock.calls[0]![0].message["zh-CN"]).toContain("已在本地退出"); expect(readConfigFile()).toMatchObject({ api_key: MODEL_KEY, base_url: "https://model.example.test", @@ -1410,7 +1587,7 @@ describe("Profile references, login and domain-specific logout", () => { ); await expect(instance.provider.getCredential()).rejects.toBeInstanceOf(CredentialError); expect(await instance.auth.logout("aliyun")).toBe(false); - expect(transport).toHaveBeenCalledTimes(2); + expect(transport).toHaveBeenCalledTimes(1); }); test.each(["console", "openapi"] as const)( @@ -1664,6 +1841,7 @@ describe("OAuth credential binding regressions", () => { sessionRef: REFERENCE, configurationFingerprint: oauthConfigurationFingerprint(profile()), }; + transport.mockResolvedValueOnce(new Response(null, { status: 204 })); await instance.auth.loginAliyun( profile(), session({ @@ -1680,7 +1858,8 @@ describe("OAuth credential binding regressions", () => { await instance.provider.saveConsoleCredential(oldCredential); expect(instance.values.get(nextReference)).toBe(before); expect((await instance.provider.getConsoleCredential(TARGET))?.token).toBe("new-console"); - expect(transport).not.toHaveBeenCalled(); + expect(transport).toHaveBeenCalledTimes(1); + expect(new URL(endpointUrl(transport.mock.calls[0]![0])).pathname).toBe("/v1/revoke"); }); test("endpoint changes during STS exchange stop the caller and preserve new metadata", async () => { From ef4558c21c9c0a865084449edecd12c604e36bc5 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Tue, 1 Dec 2026 23:13:06 +0800 Subject: [PATCH 12/13] chore(release): prepare 2.16.0 --- CHANGELOG.md | 18 ++++++++++++++++++ CHANGELOG.zh.md | 18 ++++++++++++++++++ packages/bailian-kb-dsh/package.json | 2 +- packages/bailian-memo-dsh/package.json | 2 +- packages/cli/package.json | 2 +- packages/commands/package.json | 2 +- packages/core/package.json | 2 +- packages/kscli/package.json | 2 +- packages/runtime/package.json | 2 +- skills/bailian-cli/SKILL.md | 2 +- skills/bailian-finetune/SKILL.md | 2 +- skills/bailian-gen/SKILL.md | 2 +- skills/bailian-knowledge/SKILL.md | 2 +- skills/bailian-managed-agent/SKILL.md | 2 +- skills/bailian-memory/SKILL.md | 2 +- skills/bailian-opd/SKILL.md | 2 +- skills/bailian-protocol/SKILL.md | 2 +- skills/bailian-sandbox/SKILL.md | 2 +- skills/bailian-web-search/SKILL.md | 2 +- 19 files changed, 53 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d9377e36..561e9b3ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and [中文版](CHANGELOG.zh.md) · [README](README.md) · [Contributing](CONTRIBUTING.md) +## [2.16.0] - 2026-12-01 + +> Aliyun OAuth login: `bl auth login --oauth` exchanges a browser authorization for an auto-renewing console session. + +### Added + +- **Aliyun OAuth login**: `bl auth login --oauth` signs in with an Aliyun account (China site by default; `--console-site international` for the international site) and keeps the console session and OpenAPI credentials renewed automatically. OAuth credentials coexist with API key, console and AK/SK credentials. + - `--no-browser` prints the authorization URL for another device; paste the full callback URL back to finish login without a local port listener. + +### Changed + +- **`bl auth generate-access-token`**: AK/SK flags are now optional — the command reuses saved OpenAPI credentials (including OAuth-managed sessions); `--access-key-id` / `--access-key-secret` are only needed when no credentials are stored. +- **`bl auth status`**: reports the Aliyun OAuth session and OAuth-managed console/OpenAPI credentials. + +### Fixed + +- **Token Plan international routing**: `bl token-plan` commands recognize the international Model Studio endpoint (`modelstudio.ap-southeast-1.aliyuncs.com`) and route to the intl OpenAPI host instead of misrouting by region preset. + ## [2.15.0] - 2026-12-01 ### Added diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 89b91262d..3dd09f907 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -6,6 +6,24 @@ [English](CHANGELOG.md) · [README](README.zh.md) · [参与贡献](CONTRIBUTING.zh.md) +## [2.16.0] - 2026-12-01 + +> 阿里云 OAuth 登录:`bl auth login --oauth` 通过浏览器授权换取自动续期的控制台会话。 + +### 新增 + +- **阿里云 OAuth 登录**:`bl auth login --oauth` 使用阿里云账号登录(默认中国站;国际站使用 `--console-site international`),控制台会话与 OpenAPI 凭证自动续期。OAuth 凭证与 API Key、控制台、AK/SK 凭证可共存。 + - `--no-browser` 打印授权地址供其它设备授权,粘贴完整回调 URL 即可完成登录,不监听本地端口。 + +### 变更 + +- **`bl auth generate-access-token`**:AK/SK 参数改为可选——命令复用已保存的 OpenAPI 凭证(含 OAuth 托管会话);仅在未保存凭证时才需要 `--access-key-id` / `--access-key-secret`。 +- **`bl auth status`**:展示阿里云 OAuth 会话与 OAuth 托管的控制台/OpenAPI 凭证。 + +### 修复 + +- **Token Plan 国际站路由**:`bl token-plan` 命令识别国际站 Model Studio 端点(`modelstudio.ap-southeast-1.aliyuncs.com`),正确路由到 intl OpenAPI 主机,不再因区域预设误判。 + ## [2.15.0] - 2026-12-01 ### 新增 diff --git a/packages/bailian-kb-dsh/package.json b/packages/bailian-kb-dsh/package.json index d3827496c..647f710e4 100644 --- a/packages/bailian-kb-dsh/package.json +++ b/packages/bailian-kb-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-kb-dsh", - "version": "2.15.0", + "version": "2.16.0", "description": "Bailian knowledge-base tools for DeepSeek Harness: kb_search and kb_chat over the DashScope RAG API, plus the bl CLI management skill.", "keywords": [ "alibaba-cloud", diff --git a/packages/bailian-memo-dsh/package.json b/packages/bailian-memo-dsh/package.json index 302efebab..570761052 100644 --- a/packages/bailian-memo-dsh/package.json +++ b/packages/bailian-memo-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-memo-dsh", - "version": "2.15.0", + "version": "2.16.0", "description": "Bailian personal memory for DeepSeek Harness: automatic recall, silent curation, and user-controlled remember/forget.", "keywords": [ "alibaba-cloud", diff --git a/packages/cli/package.json b/packages/cli/package.json index 158dc6666..61b5e4829 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli", - "version": "2.15.0", + "version": "2.16.0", "description": "CLI for Aliyun Model Studio (DashScope) AI Platform.", "keywords": [ "agent", diff --git a/packages/commands/package.json b/packages/commands/package.json index 039c731c1..ed9510c8b 100644 --- a/packages/commands/package.json +++ b/packages/commands/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-commands", - "version": "2.15.0", + "version": "2.16.0", "description": "Command library for bailian-cli products (knowledge, memory, media, …). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/core/package.json b/packages/core/package.json index 6253a38dc..c460e3ee0 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-core", - "version": "2.15.0", + "version": "2.16.0", "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/kscli/package.json b/packages/kscli/package.json index 20dd76d08..564662696 100644 --- a/packages/kscli/package.json +++ b/packages/kscli/package.json @@ -1,6 +1,6 @@ { "name": "knowledge-studio-cli", - "version": "2.15.0", + "version": "2.16.0", "description": "Lightweight RAG CLI for Aliyun Model Studio — focused on knowledge-base retrieval.", "keywords": [ "alibaba-cloud", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 5b514ee00..25de95620 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-runtime", - "version": "2.15.0", + "version": "2.16.0", "description": "Runtime framework for bailian-cli (createCli, registry, args, output, pipeline). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 42b5d127b..73595dc23 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-cli metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-finetune/SKILL.md b/skills/bailian-finetune/SKILL.md index 7c5044785..bc5b350d5 100644 --- a/skills/bailian-finetune/SKILL.md +++ b/skills/bailian-finetune/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-finetune metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 7e19e1a9e..370e40faf 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-gen metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-knowledge/SKILL.md b/skills/bailian-knowledge/SKILL.md index 06f781d5a..675124dd5 100644 --- a/skills/bailian-knowledge/SKILL.md +++ b/skills/bailian-knowledge/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-knowledge metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-managed-agent/SKILL.md b/skills/bailian-managed-agent/SKILL.md index 0eef5fd1d..e8a1473f6 100644 --- a/skills/bailian-managed-agent/SKILL.md +++ b/skills/bailian-managed-agent/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-managed-agent metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-memory/SKILL.md b/skills/bailian-memory/SKILL.md index 794d9d8c0..5da8526b0 100644 --- a/skills/bailian-memory/SKILL.md +++ b/skills/bailian-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-memory metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-opd/SKILL.md b/skills/bailian-opd/SKILL.md index ed289a63e..94c1a4e01 100644 --- a/skills/bailian-opd/SKILL.md +++ b/skills/bailian-opd/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-opd metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl", "node"] description: >- diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index b591e10f5..f01615e2f 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-protocol metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-sandbox/SKILL.md b/skills/bailian-sandbox/SKILL.md index c0554c00c..b84abbbbd 100644 --- a/skills/bailian-sandbox/SKILL.md +++ b/skills/bailian-sandbox/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-sandbox metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-web-search/SKILL.md b/skills/bailian-web-search/SKILL.md index 5f48a29cf..4ab65c643 100644 --- a/skills/bailian-web-search/SKILL.md +++ b/skills/bailian-web-search/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-web-search metadata: - version: "2.15.0" + version: "2.16.0" requires: bins: ["bl"] description: >- From 2f143e8c8a511058b791d673a5caa49f5bdfb375 Mon Sep 17 00:00:00 2001 From: "lisheng.lisheng" Date: Wed, 2 Dec 2026 07:50:26 +0800 Subject: [PATCH 13/13] feat(auth): build in online OAuth defaults per site and open international login Embed the production IAM client IDs and signin/oauth endpoints for both sites so a first online login needs no endpoint flags; --client-id and --authorization-url become optional overrides. Drop the international online usage block (app approved, same client ID as pre-release); the pre-release endpoint gates stay unchanged. Update unit/e2e contracts, bilingual READMEs, the auth-change guide and the skill reference. --- README.md | 12 +- README.zh.md | 12 +- docs/agents/auth-change.md | 2 +- packages/cli/README.md | 10 +- packages/cli/README.zh.md | 10 +- .../src/commands/auth/aliyun-flags.ts | 13 +- packages/commands/src/commands/auth/aliyun.ts | 55 +++---- packages/commands/tests/auth-aliyun.test.ts | 144 +++++++++++++----- packages/commands/tests/e2e/auth.e2e.test.ts | 57 +++++-- packages/core/src/auth/aliyun-config.ts | 5 + packages/core/src/auth/index.ts | 4 + packages/core/src/config/control-plane.ts | 8 +- skills/bailian-cli/reference/auth.md | 6 +- 13 files changed, 210 insertions(+), 128 deletions(-) diff --git a/README.md b/README.md index a14497258..a19e81a9b 100644 --- a/README.md +++ b/README.md @@ -193,19 +193,17 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ### Aliyun OAuth -`bl auth login --oauth` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. `--console-site ` selects the site (default `domestic`). For a first domestic online login, provide the confirmed production application ID and authorization URL: +`bl auth login --oauth` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. `--console-site ` selects the site (default `domestic`). The official IAM application ID and the authorization/token endpoints are built in for both sites, so a first online login needs no endpoint flags: ```bash -bl auth login --oauth --config aliyun \ - --client-id \ - --authorization-url +bl auth login --oauth --config aliyun ``` Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. `--console-region ` only sets the `console_region` saved to config.json and the Console routing; the OAuth authorization/token/exchange endpoints follow the site alone. It defaults to `cn-beijing` for domestic and `ap-southeast-1` for international. -International site: `bl auth login --oauth --console-site international`. The international pre-release IAM application is approved and its client ID is built in, but the remaining pre-release endpoints are not confirmed yet, so login stays blocked until they are filled in; `--dry-run` lists the missing items offline. International production login is not available yet because the production application has not been approved. +International site: `bl auth login --oauth --console-site international`. The international IAM application is approved for both pre-release and production with its client ID built in; online login automatically uses the international signin/oauth domains, and pre-release login works like the domestic one. For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth login --oauth --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. @@ -213,11 +211,11 @@ For SSH, containers or other environments without a browser, add `--no-browser`. bl auth login --oauth --config aliyun --no-browser ``` -The example reuses an already configured OAuth Profile; first online login still requires `--client-id` and `--authorization-url`. +The example works for a first login too; `--client-id` and `--authorization-url` are optional overrides of the built-in defaults. #### Domestic pre-release control plane -Set `BAILIAN_PRE=1` (or `true`) to select the pre-release control plane: domestic `cn-beijing`, or international `ap-southeast-1` with `--console-site international` (blocked until the international endpoint group is confirmed). Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. +Set `BAILIAN_PRE=1` (or `true`) to select the pre-release control plane: domestic `cn-beijing`, or international `ap-southeast-1` with `--console-site international`. Unset, empty, `0` or `false` selects the online environment. Pre-release Profiles live under a separate `pre/` config directory and do not inherit online Console credentials or general AK/SK environment variables. DashScope inference keeps its existing connection and Profile selection. ```bash BAILIAN_PRE=1 bl auth login --oauth --dry-run diff --git a/README.zh.md b/README.zh.md index b902d54cd..6a21d4eb5 100644 --- a/README.zh.md +++ b/README.zh.md @@ -192,19 +192,17 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ### 阿里云 OAuth -`bl auth login --oauth` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。`--console-site ` 选择站点(缺省 `domestic`)。首次在国内线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: +`bl auth login --oauth` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。`--console-site ` 选择站点(缺省 `domestic`)。正式 IAM 应用 ID 与授权/换票端点已按站点内置,线上首次登录无需任何端点参数: ```bash -bl auth login --oauth --config aliyun \ - --client-id <正式应用ID> \ - --authorization-url <已确认的授权地址> +bl auth login --oauth --config aliyun ``` IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。`--console-region ` 只决定写入 config.json 的 `console_region` 与控制台路由;OAuth 授权/换票端点仅由站点决定。缺省按站点推导:国内 `cn-beijing`,国际 `ap-southeast-1`。 -国际站:`bl auth login --oauth --console-site international`。国际预发 IAM 应用已获批,client ID 已内置;其余预发端点尚未确认,确认填入前登录保持阻断,`--dry-run` 可离线列出缺失项。国际站线上应用未申请,线上登录尚未开放。 +国际站:`bl auth login --oauth --console-site international`。国际站预发与线上 IAM 应用均已获批,client ID 已内置;线上登录自动使用国际站 signin/oauth 域名,预发登录方式与国内一致。 SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth login --oauth --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 @@ -212,11 +210,11 @@ SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑 bl auth login --oauth --config aliyun --no-browser ``` -示例复用已配置的 OAuth Profile;线上首次登录仍须提供 `--client-id` 和 `--authorization-url`。 +示例同样适用于首次登录;`--client-id` 与 `--authorization-url` 仅用于覆盖内置默认。 #### 国内预发控制面 -用 `BAILIAN_PRE=1`(也接受 `true`)切换预发控制面:国内 `cn-beijing`,或配合 `--console-site international` 使用国际 `ap-southeast-1`(国际端点组确认前保持阻断);未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 +用 `BAILIAN_PRE=1`(也接受 `true`)切换预发控制面:国内 `cn-beijing`,或配合 `--console-site international` 使用国际 `ap-southeast-1`;未设置、空值、`0` 或 `false` 使用线上。预发 Profile 独立保存在配置目录下的 `pre/`,不会复用线上控制台凭据或通用 AK/SK 环境变量。DashScope 推理的连接和 Profile 选择不变。 ```bash BAILIAN_PRE=1 bl auth login --oauth --dry-run diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index a4c4e8ddc..9f3c53f1a 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -81,7 +81,7 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - OAuth 入口是 `bl auth login --oauth [--console-site ] [--console-region ]`,与 `--api-key` / `--console` / `--open-api` 并列为第四种登录模式;7 个 OAuth 专属 flag(`--client-id` / `--scope` / `--oauth-base-url` / `--authorization-url` / `--modelstudio-host` / `--console-gateway` / `--bailiancontrol-host`)定义在 `auth/aliyun-flags.ts`,脱离 `--oauth` 报用法错误。旧 `bl auth --login aliyun` 根入口已移除(仅 beta 存在过,无 stable 兼容负担);`aliyun.ts` 只保留 `runAliyunOAuthLogin` 与 loginPlan,不再是 defineCommand。 - 默认 OAuth 回调仅监听 `127.0.0.1` 随机端口的 `/oauth/callback` 路径,授权请求与换票使用同一 `redirect_uri`。IAM 登记 `http://127.0.0.1:12345/oauth/callback`;NativeApp 忽略回环端口,但协议、主机和路径必须一致,不保留根路径兼容。 - OAuth 的 `--no-browser` 显式选择跨设备手动授权:固定使用已登记的 `http://127.0.0.1:12345/oauth/callback`,不启服务器,在原进程粘贴完整回调 URL;校验地址、唯一且匹配的 state、唯一非空 code,拒绝 userinfo、fragment、非法查询编码、解码后包含控制字符的查询与其它登录会话。有可关闭回显的 TTY 时隐藏输入,非 TTY 提示上游终端可能回显;不保存输入历史。错误输入可重试但不重新生成 state/PKCE;有效 state 的授权拒绝、EOF、超长输入、Ctrl+C、Ctrl+Z 或超时结束登录。与默认流共用换票、落盘及取消处理,不自动降级、不提供设备码流程,不改变 `auth login --console --no-browser` 的本机回调语义。 -- 线上首次登录必须显式配置正式 OAuth 应用 ID 和授权 URL,之后可复用选中 Profile(仅同 site 复用);端点维持显式参数 > Profile > 默认地址。`--console-region` 只决定写入 config.json 的 `console_region` 与控制台路由(REGION_GATEWAYS 四组合齐全),缺省按 site 推导(domestic→cn-beijing,international→ap-southeast-1),显式值自由覆盖、不做 site×region 配对拒绝;OAuth 前三跳(signin/token/exchange)端点仅由 site 决定。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和按 site 分组的端点常量(`control-plane.ts` 的 `PRE_DOMESTIC_GROUP` / `PRE_INTL_GROUP`),不读线上控制面凭据、不隐式回退、不改 hosts/代理。国际预发 IAM 应用已获批(client ID 内置 `PRE_INTL_ALIYUN_CLI_CLIENT_ID`),六端点已于 2026-11-30 全部确认填入 `PRE_INTL_GROUP`(两个 OpenAPI host 由服务端确认;OpenAPI 域名是 region 模板 `modelstudio.{region_id}.aliyuncs.com` / `bailiancontrol.{region_id}.aliyuncs.com`,不区分站点,只有控制台路由区分站点,`resolvePreOpenApiHost` 须同时接受线上区域域名与预发域名)。`intlPreEndpointsConfirmed()` 闸门保留:任一常量回退 undefined 时 live 抛 `unconfirmedIntlPreError()` 双语阻断、dry-run 计入 missing,零网络零写盘;**禁止猜测域名**,新端点仅服务端确认后填入。`BAILIAN_PRE_CONSOLE_ORIGIN/GATEWAY` 在 env 解析期只校验值属于某个已确认站点组,site×value 一致性由命令期 `requirePreEndpoint` 校验。国际线上应用未申请,`international × online` 硬阻断(dry-run 同样报错)。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 +- 线上登录的正式 IAM 应用 ID 与授权/换票端点已按站点内置(`aliyun-config.ts`:国内 `ALIYUN_CLI_CLIENT_ID` + signin.aliyun.com/oauth.aliyun.com,国际 `INTL_ALIYUN_CLI_CLIENT_ID` + signin.alibabacloud.com/oauth.alibabacloud.com),首次登录零端点参数即可走通;`--client-id` / `--authorization-url` 等为可选覆盖,端点优先级维持显式参数 > Profile > 按站点内置默认;已存 Profile 仅同 site 复用。`--console-region` 只决定写入 config.json 的 `console_region` 与控制台路由(REGION_GATEWAYS 四组合齐全),缺省按 site 推导(domestic→cn-beijing,international→ap-southeast-1),显式值自由覆盖、不做 site×region 配对拒绝;OAuth 前三跳(signin/token/exchange)端点仅由 site 决定。预发模式由 `bl` 入口解析 `BAILIAN_PRE` 后传入 core/runtime,使用独立配置路径和按 site 分组的端点常量(`control-plane.ts` 的 `PRE_DOMESTIC_GROUP` / `PRE_INTL_GROUP`),不读线上控制面凭据、不隐式回退、不改 hosts/代理。国际预发 IAM 应用已获批(client ID 内置 `PRE_INTL_ALIYUN_CLI_CLIENT_ID`),六端点已于 2026-11-30 全部确认填入 `PRE_INTL_GROUP`(两个 OpenAPI host 由服务端确认;OpenAPI 域名是 region 模板 `modelstudio.{region_id}.aliyuncs.com` / `bailiancontrol.{region_id}.aliyuncs.com`,不区分站点,只有控制台路由区分站点,`resolvePreOpenApiHost` 须同时接受线上区域域名与预发域名)。`intlPreEndpointsConfirmed()` 闸门保留:任一常量回退 undefined 时 live 抛 `unconfirmedIntlPreError()` 双语阻断、dry-run 计入 missing,零网络零写盘;**禁止猜测域名**,新端点仅服务端确认后填入。`BAILIAN_PRE_CONSOLE_ORIGIN/GATEWAY` 在 env 解析期只校验值属于某个已确认站点组,site×value 一致性由命令期 `requirePreEndpoint` 校验。国际 IAM 应用预发与线上均已获批,两段式共用同一 client ID(内置 `INTL_ALIYUN_CLI_CLIENT_ID`,`PRE_INTL_ALIYUN_CLI_CLIENT_ID` 是其别名),`international × online` 已放开并自动使用国际线上端点。Console 浏览器登录与 Bearer 网关须分别确认后显式配置;未确认的预发管理接口必须联网前阻断。MCP 管理和云端 Skill 沿用 API Key 与工作空间路由,不切换到预发。模型域来源和 `kscli` 不受开关影响。 - `aliyun_oauth` 仅保存端点、client_id/scope、会话引用、域激活状态及到期元数据;OAuth AT 不覆盖旧的 Console `access_token`。凭据存于配置目录下独立的 `oauth/.json` 明文文件,绑定会话引用,不写入主配置。Unix 校验目录 `0700` 和文件 `0600` 及所有者,Windows 校验私有 ACL;拒绝非普通文件及链接,使用同目录唯一临时文件、fsync 和原子替换。旧加密会话不迁移,需要重新登录。 - 同一个异步 OpenAPI provider 负责 OAuth AT/RT→STS,Console 换票与 OpenAPI 签名前复用。优先级保持 flag > 百炼 env > 所选 file(静态或 OAuth)> 阿里云 env;临时来源不落盘。`describe/stored` 只读元数据,不读取凭据文件;静态 dry-run 不调用 OAuth,框架更新/遥测仍遵循原设置。 - `/v1/exchange` 接受完整的 PascalCase 或 camelCase STS 字段,不跨两套字段拼接。两种格式均校验非空字符串凭据及未来到期时间,不输出原始响应体。 diff --git a/packages/cli/README.md b/packages/cli/README.md index e30b412d0..a19e81a9b 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -193,19 +193,17 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ### Aliyun OAuth -`bl auth login --oauth` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. `--console-site ` selects the site (default `domestic`). For a first domestic online login, provide the confirmed production application ID and authorization URL: +`bl auth login --oauth` uses authorization code + PKCE, exchanges OAuth credentials for STS, and uses STS to obtain the Bailian Console token and sign OpenAPI requests. `--console-site ` selects the site (default `domestic`). The official IAM application ID and the authorization/token endpoints are built in for both sites, so a first online login needs no endpoint flags: ```bash -bl auth login --oauth --config aliyun \ - --client-id \ - --authorization-url +bl auth login --oauth --config aliyun ``` Register `http://127.0.0.1:12345/oauth/callback` as the IAM redirect URI. NativeApp loopback callbacks allow a random port, but the scheme, host and path must match. The CLI accepts only `/oauth/callback`, not the root path or an extra trailing `/`. Online endpoints resolve in the order explicit flags > selected Profile > defaults. Later logins can reuse the saved application ID and endpoints. `--dry-run` previews the plan without opening a browser, reading credential files or exchanging credentials. `--console-region ` only sets the `console_region` saved to config.json and the Console routing; the OAuth authorization/token/exchange endpoints follow the site alone. It defaults to `cn-beijing` for domestic and `ap-southeast-1` for international. -International site: `bl auth login --oauth --console-site international`. The international pre-release IAM application is approved, its client ID is built in, and all pre-release endpoints are confirmed, so pre-release login works like the domestic one. International production login is not available yet because the production application has not been approved. +International site: `bl auth login --oauth --console-site international`. The international IAM application is approved for both pre-release and production with its client ID built in; online login automatically uses the international signin/oauth domains, and pre-release login works like the domestic one. For SSH, containers or other environments without a browser, add `--no-browser`. Open the generated link on a computer or phone, authorize, then paste the entire redirected URL (including `code` and `state`) back into the same CLI session. The callback is `http://127.0.0.1:12345/oauth/callback`; no port is opened and the browser's connection error is expected. Input is hidden only when the CLI can disable echo on a terminal; otherwise it warns that the callback URL may be visible. For interactive SSH, use `ssh -t user@host 'bl auth login --oauth --no-browser'`; in Docker, allocate a TTY with `docker exec -it`. The CLI does not save the URL in input history. This is interactive cross-device authorization, not device-code login or unattended CI authentication. @@ -213,7 +211,7 @@ For SSH, containers or other environments without a browser, add `--no-browser`. bl auth login --oauth --config aliyun --no-browser ``` -The example reuses an already configured OAuth Profile; first online login still requires `--client-id` and `--authorization-url`. +The example works for a first login too; `--client-id` and `--authorization-url` are optional overrides of the built-in defaults. #### Domestic pre-release control plane diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index a99d37491..6a21d4eb5 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -192,19 +192,17 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ### 阿里云 OAuth -`bl auth login --oauth` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。`--console-site ` 选择站点(缺省 `domestic`)。首次在国内线上环境登录时,请提供已确认的正式 OAuth 应用 ID 和授权地址: +`bl auth login --oauth` 使用授权码与 PKCE 获取 OAuth 凭据,再置换 STS;STS 同时用于获取百炼 Console token 和签名调用 OpenAPI。`--console-site ` 选择站点(缺省 `domestic`)。正式 IAM 应用 ID 与授权/换票端点已按站点内置,线上首次登录无需任何端点参数: ```bash -bl auth login --oauth --config aliyun \ - --client-id <正式应用ID> \ - --authorization-url <已确认的授权地址> +bl auth login --oauth --config aliyun ``` IAM 重定向 URI 应登记为 `http://127.0.0.1:12345/oauth/callback`。NativeApp 本机回环回调允许随机端口,但协议、主机和路径必须一致;CLI 仅接受 `/oauth/callback`,不接受根路径或末尾额外的 `/`。 线上端点按显式参数 > 所选 Profile > 默认地址解析;之后可以复用已保存的应用 ID 和端点。`--dry-run` 仅展示计划,不打开浏览器、不读凭据文件、不换票。`--console-region ` 只决定写入 config.json 的 `console_region` 与控制台路由;OAuth 授权/换票端点仅由站点决定。缺省按站点推导:国内 `cn-beijing`,国际 `ap-southeast-1`。 -国际站:`bl auth login --oauth --console-site international`。国际预发 IAM 应用已获批,client ID 已内置,预发端点已全部确认,预发登录方式与国内一致。国际站线上应用未申请,线上登录尚未开放。 +国际站:`bl auth login --oauth --console-site international`。国际站预发与线上 IAM 应用均已获批,client ID 已内置;线上登录自动使用国际站 signin/oauth 域名,预发登录方式与国内一致。 SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑或手机上打开本次生成的链接并授权,再把地址栏中完整的回调 URL(含 `code` 和 `state`)粘回同一个 CLI 会话。回调地址为 `http://127.0.0.1:12345/oauth/callback`,不监听端口,浏览器提示连接失败是正常现象。只有 CLI 能关闭终端回显时才隐藏输入,否则会提醒回调 URL 可能被显示。通过 SSH 交互登录时,用 `ssh -t user@host 'bl auth login --oauth --no-browser'`;在 Docker 里,用 `docker exec -it` 分配 TTY。CLI 不会把回调 URL 保存到输入历史。这仍需人工授权,不是设备码登录或无人值守的 CI 鉴权。 @@ -212,7 +210,7 @@ SSH、容器等无法打开浏览器的环境可加 `--no-browser`:在电脑 bl auth login --oauth --config aliyun --no-browser ``` -示例复用已配置的 OAuth Profile;线上首次登录仍须提供 `--client-id` 和 `--authorization-url`。 +示例同样适用于首次登录;`--client-id` 与 `--authorization-url` 仅用于覆盖内置默认。 #### 国内预发控制面 diff --git a/packages/commands/src/commands/auth/aliyun-flags.ts b/packages/commands/src/commands/auth/aliyun-flags.ts index 2d8fc8758..6ee457d04 100644 --- a/packages/commands/src/commands/auth/aliyun-flags.ts +++ b/packages/commands/src/commands/auth/aliyun-flags.ts @@ -1,6 +1,7 @@ import { ALIYUN_CLI_SCOPE, ALIYUN_OAUTH_BASE_URL, + INTL_ALIYUN_OAUTH_BASE_URL, resolveConsoleGatewayOrigin, resolveModelStudioHost, type FlagsDef, @@ -15,8 +16,8 @@ export const ALIYUN_OAUTH_LOGIN_FLAGS = { type: "string", valueHint: "", description: { - "en-US": "OAuth client ID; required for the first login outside pre-release", - "zh-CN": "OAuth 客户端 ID;非预发环境首次登录必须提供", + "en-US": "OAuth client ID override (built-in default per site)", + "zh-CN": "OAuth 客户端 ID 覆盖(按站点内置默认)", }, }, scope: { @@ -31,16 +32,16 @@ export const ALIYUN_OAUTH_LOGIN_FLAGS = { type: "string", valueHint: "", description: { - "en-US": `OAuth token service origin (production default: ${ALIYUN_OAUTH_BASE_URL})`, - "zh-CN": `OAuth 令牌服务源站(线上默认:${ALIYUN_OAUTH_BASE_URL})`, + "en-US": `OAuth token service origin (default: ${ALIYUN_OAUTH_BASE_URL}; international: ${INTL_ALIYUN_OAUTH_BASE_URL})`, + "zh-CN": `OAuth 令牌服务源站(默认:${ALIYUN_OAUTH_BASE_URL};国际站:${INTL_ALIYUN_OAUTH_BASE_URL})`, }, }, authorizationUrl: { type: "string", valueHint: "", description: { - "en-US": "Explicit authorization URL; required for the first login outside pre-release", - "zh-CN": "显式授权地址;非预发环境首次登录必须提供", + "en-US": "Authorization URL override (built-in default per site)", + "zh-CN": "授权地址覆盖(按站点内置默认)", }, }, modelstudioHost: { diff --git a/packages/commands/src/commands/auth/aliyun.ts b/packages/commands/src/commands/auth/aliyun.ts index 89e8cafb8..657710932 100644 --- a/packages/commands/src/commands/auth/aliyun.ts +++ b/packages/commands/src/commands/auth/aliyun.ts @@ -2,16 +2,19 @@ import http from "node:http"; import { createInterface } from "node:readline"; import { PassThrough, type Readable } from "node:stream"; import { + ALIYUN_AUTHORIZATION_URL, ALIYUN_CLI_CLIENT_ID, ALIYUN_CLI_SCOPE, ALIYUN_OAUTH_BASE_URL, BailianError, ExitCode, + INTL_ALIYUN_AUTHORIZATION_URL, + INTL_ALIYUN_CLI_CLIENT_ID, + INTL_ALIYUN_OAUTH_BASE_URL, PRE_ALIYUN_AUTHORIZATION_URL, PRE_ALIYUN_OAUTH_BASE_URL, PRE_BAILIAN_CONTROL_HOST, PRE_INTL_ALIYUN_AUTHORIZATION_URL, - PRE_INTL_ALIYUN_CLI_CLIENT_ID, PRE_INTL_ALIYUN_OAUTH_BASE_URL, PRE_INTL_BAILIAN_CONTROL_HOST, PRE_INTL_MODEL_STUDIO_HOST, @@ -117,11 +120,7 @@ function loginPlan( const clientId = options.clientId ?? saved?.client_id ?? - (pre - ? site === "international" - ? PRE_INTL_ALIYUN_CLI_CLIENT_ID - : ALIYUN_CLI_CLIENT_ID - : undefined); + (site === "international" ? INTL_ALIYUN_CLI_CLIENT_ID : ALIYUN_CLI_CLIENT_ID); const scope = nonempty(options.scope ?? saved?.scope ?? ALIYUN_CLI_SCOPE, "--scope"); const region = nonempty( options.consoleRegion ?? @@ -130,7 +129,7 @@ function loginPlan( defaultConsoleRegion(site), "--console-region", ); - const normalizedClientId = clientId === undefined ? undefined : nonempty(clientId, "--client-id"); + const normalizedClientId = nonempty(clientId, "--client-id"); const domains = { console_region: region, ...(site === "international" ? { console_site: site } : {}), @@ -214,12 +213,10 @@ function loginPlan( ...domains, }; } - if (site === "international") { - throw new UsageError( - "International production OAuth login is not available yet; the production application has not been approved. / 国际站线上 OAuth 登录尚未开放(线上应用未申请)。", - ); - } - const authorizationUrl = options.authorizationUrl ?? saved?.authorization_url; + const authorizationUrl = + options.authorizationUrl ?? + saved?.authorization_url ?? + (site === "international" ? INTL_ALIYUN_AUTHORIZATION_URL : ALIYUN_AUTHORIZATION_URL); const modelstudioHost = options.modelstudioHost ?? saved?.modelstudio_host ?? @@ -232,11 +229,12 @@ function loginPlan( client_id: normalizedClientId, scope, oauth_base_url: normalizeOAuthUrl( - options.oauthBaseUrl ?? saved?.oauth_base_url ?? ALIYUN_OAUTH_BASE_URL, + options.oauthBaseUrl ?? + saved?.oauth_base_url ?? + (site === "international" ? INTL_ALIYUN_OAUTH_BASE_URL : ALIYUN_OAUTH_BASE_URL), true, ), - authorization_url: - authorizationUrl === undefined ? undefined : normalizeOAuthUrl(authorizationUrl), + authorization_url: normalizeOAuthUrl(authorizationUrl), modelstudio_host: normalizeOpenApiHost(modelstudioHost), console_gateway: normalizeOAuthUrl(consoleGateway, true), ...(bailiancontrolHost === undefined @@ -655,12 +653,10 @@ export async function runAliyunOAuthLogin( ); const missing = [ ...(!plan.authorization_url ? ["--authorization-url"] : []), - ...(!plan.client_id ? ["--client-id"] : []), ...(!plan.console_gateway ? ["BAILIAN_PRE_CONSOLE_GATEWAY"] : []), ]; const config = deps.settings.configName ?? "default"; if (dryRun) { - const missingClientId = missing.includes("--client-id"); const unverifiedGateway = !!options.consoleGateway && !plan.console_gateway; const unverifiedNote = unverifiedGateway ? localize(deps, { @@ -692,30 +688,13 @@ export async function runAliyunOAuthLogin( }, { text: localize(deps, { - "en-US": `Would authorize Aliyun OAuth ${options.noBrowser ? "by pasting the callback URL without listening on a port" : "with a random loopback port"}, exchange STS, validate Console access and save the session. ${missingClientId ? "Missing required options" : "Missing endpoints"}: ${missing.join(", ") || "none"}.${preEndpoints}${unverifiedNote}`, - "zh-CN": `将${options.noBrowser ? "通过粘贴回调 URL(不监听端口)" : "通过随机回环端口"}完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。${missingClientId ? "缺少必填选项" : "缺少端点"}:${missing.join("、") || "无"}。${preEndpoints}${unverifiedNote}`, + "en-US": `Would authorize Aliyun OAuth ${options.noBrowser ? "by pasting the callback URL without listening on a port" : "with a random loopback port"}, exchange STS, validate Console access and save the session. Missing endpoints: ${missing.join(", ") || "none"}.${preEndpoints}${unverifiedNote}`, + "zh-CN": `将${options.noBrowser ? "通过粘贴回调 URL(不监听端口)" : "通过随机回环端口"}完成阿里云 OAuth 授权、置换 STS、校验控制台并保存会话。缺少端点:${missing.join("、") || "无"}。${preEndpoints}${unverifiedNote}`, }), }, ); return; } - if (!plan.client_id) { - throw new UsageError( - localize(deps, { - "en-US": `Provide ${missing.join(" and ")} for the first login outside the pre-release control plane.`, - "zh-CN": `非预发控制面首次登录请提供 ${missing.join(" 和 ")}。`, - }), - ); - } - if (!plan.authorization_url) { - throw new UsageError( - localize(deps, { - "en-US": - "Provide --authorization-url for the first login; the authorization endpoint will not be guessed.", - "zh-CN": "首次登录请提供 --authorization-url;不会猜测授权地址。", - }), - ); - } if ( options.callbackTimeoutMs !== undefined && (!Number.isFinite(options.callbackTimeoutMs) || options.callbackTimeoutMs <= 0) @@ -725,7 +704,7 @@ export async function runAliyunOAuthLogin( const profile: LoginProfile = { ...plan, client_id: plan.client_id, - authorization_url: plan.authorization_url, + authorization_url: plan.authorization_url!, // Live preflight above requires confirmed endpoints and a configured gateway; // only dry-run may omit them. oauth_base_url: plan.oauth_base_url!, diff --git a/packages/commands/tests/auth-aliyun.test.ts b/packages/commands/tests/auth-aliyun.test.ts index fee73a647..21e34a6c8 100644 --- a/packages/commands/tests/auth-aliyun.test.ts +++ b/packages/commands/tests/auth-aliyun.test.ts @@ -4,9 +4,13 @@ import { execFile } from "node:child_process"; import { fileURLToPath } from "node:url"; import { createHash } from "node:crypto"; import { + ALIYUN_AUTHORIZATION_URL, ALIYUN_CLI_CLIENT_ID, ALIYUN_CLI_SCOPE, ALIYUN_OAUTH_BASE_URL, + INTL_ALIYUN_AUTHORIZATION_URL, + INTL_ALIYUN_CLI_CLIENT_ID, + INTL_ALIYUN_OAUTH_BASE_URL, PRE_ALIYUN_OAUTH_BASE_URL, PRE_INTL_ALIYUN_AUTHORIZATION_URL, PRE_INTL_ALIYUN_CLI_CLIENT_ID, @@ -48,6 +52,10 @@ const DEFAULT_ENDPOINTS = { modelstudioHost: "modelstudio.cn-beijing.aliyuncs.com", consoleGateway: "https://bailian-cs.console.aliyun.com", }; +const INTL_DEFAULT_ENDPOINTS = { + modelstudioHost: "modelstudio.ap-southeast-1.aliyuncs.com", + consoleGateway: "https://bailian-singapore-cs.alibabacloud.com", +}; const PRE_CONSOLE_GATEWAY = "https://pre-bailian-cs.console.aliyun.com"; const PRE_INTL_CONSOLE_GATEWAY = "https://pre-bailian-singapore-cs.alibabacloud.com"; const SECRETS = { @@ -121,9 +129,13 @@ beforeEach(() => { const url = new URL(input instanceof Request ? input.url : input.toString()); requests.push({ url, init }); const isOAuth = - [ENDPOINTS.oauthBaseUrl, PRE_ALIYUN_OAUTH_BASE_URL, PRE_INTL_ALIYUN_OAUTH_BASE_URL].includes( - url.origin, - ) && !url.search; + [ + ENDPOINTS.oauthBaseUrl, + ALIYUN_OAUTH_BASE_URL, + INTL_ALIYUN_OAUTH_BASE_URL, + PRE_ALIYUN_OAUTH_BASE_URL, + PRE_INTL_ALIYUN_OAUTH_BASE_URL, + ].includes(url.origin) && !url.search; if (isOAuth && url.pathname === "/v1/revoke") { return new Response(null, { status: revokeFails ? 503 : 200 }); } @@ -134,6 +146,7 @@ beforeEach(() => { [ ENDPOINTS.modelstudioHost, DEFAULT_ENDPOINTS.modelstudioHost, + INTL_DEFAULT_ENDPOINTS.modelstudioHost, PRE_MODEL_STUDIO_HOST, PRE_INTL_MODEL_STUDIO_HOST, ].some((hostname) => url.href === `https://${hostname}/modelstudio/cli/generateAccessToken`) @@ -143,6 +156,7 @@ beforeEach(() => { [ ENDPOINTS.consoleGateway, DEFAULT_ENDPOINTS.consoleGateway, + INTL_DEFAULT_ENDPOINTS.consoleGateway, PRE_CONSOLE_GATEWAY, PRE_INTL_CONSOLE_GATEWAY, ].includes(url.origin) && @@ -287,7 +301,6 @@ function launch( ? AbortSignal.any([controller.signal, options.signal]) : controller.signal; const resolvedOptions = { - ...(settingsOptions.preControlPlane ? {} : { clientId: ALIYUN_CLI_CLIENT_ID }), ...(settingsOptions.omitEndpoints ? {} : ENDPOINTS), callbackTimeoutMs: 1000, ...options, @@ -1190,14 +1203,31 @@ test.each([ expect(probe.save).not.toHaveBeenCalled(); }); -test("首次登录缺授权地址在监听和请求前拒绝", async () => { - const listen = vi.spyOn(http.Server.prototype, "listen"); - const probe = launch({ authorizationUrl: undefined }); - expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); - expect(listen).not.toHaveBeenCalled(); - expect(fetchMock).not.toHaveBeenCalled(); - expect(probe.browser).not.toHaveBeenCalled(); - expect(probe.save).not.toHaveBeenCalled(); +test("线上首次登录零参数使用内置默认端点完成全链路", async () => { + const probe = launch({}, { omitEndpoints: true }); + const { authUrl } = await finish(probe); + const authorization = new URL(authUrl); + expect(authorization.origin).toBe(new URL(ALIYUN_AUTHORIZATION_URL).origin); + expect(authorization.searchParams.get("client_id")).toBe(ALIYUN_CLI_CLIENT_ID); + expect(requests.map(({ url }) => url.origin)).toEqual([ + ALIYUN_OAUTH_BASE_URL, + ALIYUN_OAUTH_BASE_URL, + `https://${DEFAULT_ENDPOINTS.modelstudioHost}`, + DEFAULT_ENDPOINTS.consoleGateway, + ]); + expect(probe.save).toHaveBeenCalledWith( + expect.objectContaining({ + client_id: ALIYUN_CLI_CLIENT_ID, + authorization_url: ALIYUN_AUTHORIZATION_URL, + oauth_base_url: ALIYUN_OAUTH_BASE_URL, + modelstudio_host: DEFAULT_ENDPOINTS.modelstudioHost, + console_gateway: DEFAULT_ENDPOINTS.consoleGateway, + console_region: "cn-beijing", + }), + expect.any(Object), + ); + assertNoSecrets(probe); + assertSignalCleanup(probe); }); test.each([ @@ -1260,7 +1290,10 @@ test.each([true, false])( const data = JSON.parse(probe.stdout.join("")); expect(data.method).toBe("aliyun"); expect(data.no_browser).toBe(omitEndpoints); - expect(data.missing).toEqual(omitEndpoints ? ["--authorization-url"] : []); + expect(data.missing).toEqual([]); + expect(data.plan.authorization_url).toBe( + omitEndpoints ? ALIYUN_AUTHORIZATION_URL : ENDPOINTS.authorizationUrl, + ); expect(data.plan.modelstudio_host).toBe( omitEndpoints ? DEFAULT_ENDPOINTS.modelstudioHost : ENDPOINTS.modelstudioHost, ); @@ -1393,21 +1426,53 @@ test("国内线上 dry-run plan 保持既有字段形状(回归基线)", asy expect(probe.save).not.toHaveBeenCalled(); }); -test.each([false, true])( - "国际站线上 OAuth 尚未开放,live 与 dry-run 均阻断 (%s)", - async (dryRun) => { - const listen = vi.spyOn(http.Server.prototype, "listen"); - const probe = launch({ consoleSite: "international" }, { dryRun }); - expect(await probe.outcome).toMatchObject({ - exitCode: ExitCode.USAGE, - message: expect.stringContaining("International production OAuth login is not available yet"), - }); - expect(listen).not.toHaveBeenCalled(); - expect(probe.browser).not.toHaveBeenCalled(); - expect(fetchMock).not.toHaveBeenCalled(); - expect(probe.save).not.toHaveBeenCalled(); - }, -); +test("国际站线上 dry-run 零参数给出内置端点与 ap-southeast-1", async () => { + const probe = launch({ consoleSite: "international" }, { dryRun: true, omitEndpoints: true }); + expect(await probe.outcome).toBeUndefined(); + const data = JSON.parse(probe.stdout.join("")); + expect(data.missing).toEqual([]); + expect(data.plan).toEqual({ + client_id: INTL_ALIYUN_CLI_CLIENT_ID, + scope: ALIYUN_CLI_SCOPE, + oauth_base_url: INTL_ALIYUN_OAUTH_BASE_URL, + authorization_url: INTL_ALIYUN_AUTHORIZATION_URL, + modelstudio_host: INTL_DEFAULT_ENDPOINTS.modelstudioHost, + console_gateway: INTL_DEFAULT_ENDPOINTS.consoleGateway, + console_region: "ap-southeast-1", + console_site: "international", + console_enabled: true, + openapi_enabled: true, + }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(probe.save).not.toHaveBeenCalled(); +}); + +test("国际站线上 OAuth 登录绑定国际线上端点,不请求国内或预发网关", async () => { + const probe = launch({ consoleSite: "international" }, { omitEndpoints: true }); + const { authUrl } = await finish(probe); + expect(new URL(authUrl).origin).toBe(new URL(INTL_ALIYUN_AUTHORIZATION_URL).origin); + expect(new URL(authUrl).searchParams.get("client_id")).toBe(INTL_ALIYUN_CLI_CLIENT_ID); + expect(requests.map(({ url }) => url.origin)).toEqual([ + INTL_ALIYUN_OAUTH_BASE_URL, + INTL_ALIYUN_OAUTH_BASE_URL, + `https://${INTL_DEFAULT_ENDPOINTS.modelstudioHost}`, + INTL_DEFAULT_ENDPOINTS.consoleGateway, + ]); + expect(probe.save).toHaveBeenCalledWith( + expect.objectContaining({ + client_id: INTL_ALIYUN_CLI_CLIENT_ID, + authorization_url: INTL_ALIYUN_AUTHORIZATION_URL, + oauth_base_url: INTL_ALIYUN_OAUTH_BASE_URL, + console_site: "international", + console_region: "ap-southeast-1", + modelstudio_host: INTL_DEFAULT_ENDPOINTS.modelstudioHost, + console_gateway: INTL_DEFAULT_ENDPOINTS.consoleGateway, + }), + expect.any(Object), + ); + assertNoSecrets(probe); + assertSignalCleanup(probe); +}); test("国际预发 live 缺网关时阻断,零监听零请求零落盘", async () => { const listen = vi.spyOn(http.Server.prototype, "listen"); @@ -1543,7 +1608,7 @@ test("线上国内显式地域覆盖落盘与网关路由,OAuth 换票端点 assertNoSecrets(probe); }); -test("跨站点重登不复用旧站点 Profile,按全新登录要求显式端点", async () => { +test("跨站点重登不复用旧站点 Profile,按全新登录使用内置默认", async () => { const previous: AliyunOAuthProfile = { client_id: "intl-stored-client", scope: "openid", @@ -1557,14 +1622,17 @@ test("跨站点重登不复用旧站点 Profile,按全新登录要求显式端 console_enabled: true, openapi_enabled: true, }; - const listen = vi.spyOn(http.Server.prototype, "listen"); - const probe = launch( - { consoleSite: "domestic", clientId: undefined, authorizationUrl: undefined }, - { omitEndpoints: true, previous }, - ); - expect(await probe.outcome).toMatchObject({ exitCode: ExitCode.USAGE }); + const probe = launch({ consoleSite: "domestic" }, { omitEndpoints: true, previous }); + const { authUrl } = await finish(probe); + expect(new URL(authUrl).searchParams.get("client_id")).toBe(ALIYUN_CLI_CLIENT_ID); expect(probe.describe).toHaveBeenCalledTimes(1); - expect(listen).not.toHaveBeenCalled(); - expect(fetchMock).not.toHaveBeenCalled(); - expect(probe.save).not.toHaveBeenCalled(); + const [profile] = probe.save.mock.calls[0]!; + expect(profile).toMatchObject({ + client_id: ALIYUN_CLI_CLIENT_ID, + authorization_url: ALIYUN_AUTHORIZATION_URL, + oauth_base_url: ALIYUN_OAUTH_BASE_URL, + console_region: "cn-beijing", + }); + expect(profile).not.toHaveProperty("console_site"); + assertNoSecrets(probe); }); diff --git a/packages/commands/tests/e2e/auth.e2e.test.ts b/packages/commands/tests/e2e/auth.e2e.test.ts index a6101509f..08f137659 100644 --- a/packages/commands/tests/e2e/auth.e2e.test.ts +++ b/packages/commands/tests/e2e/auth.e2e.test.ts @@ -75,7 +75,7 @@ describe("e2e: auth", () => { expect(result.stdout).toBe(""); }); - test("aliyun dry-run 仅返回配置计划与缺少的端点", async () => { + test("aliyun dry-run 零参数返回内置线上计划", async () => { const result = await runCommandInProcess(AUTH_ROUTES, [ "auth", "login", @@ -90,32 +90,44 @@ describe("e2e: auth", () => { plan: { client_id: string; scope: string; + authorization_url: string; + oauth_base_url: string; modelstudio_host: string; console_gateway: string; }; missing: string[]; }>(result.stdout); expect(data.method).toBe("aliyun"); - expect(data.plan.client_id).toBeUndefined(); + expect(data.plan.client_id).toBe("4001958595402383681"); expect(data.plan.scope).toBe("openid /internal/bailian/cli"); + expect(data.plan.authorization_url).toBe("https://signin.aliyun.com/oauth2/v1/auth"); + expect(data.plan.oauth_base_url).toBe("https://oauth.aliyun.com"); expect(data.plan.modelstudio_host).toBe("modelstudio.cn-beijing.aliyuncs.com"); expect(data.plan.console_gateway).toBe("https://bailian-cs.console.aliyun.com"); - expect(data.missing).toEqual(["--authorization-url", "--client-id"]); + expect(data.missing).toEqual([]); }); - test("aliyun 首次登录未给授权地址时在授权前失败", async () => { + test("aliyun dry-run 显式授权地址与客户端 ID 覆盖内置默认", async () => { const result = await runCommandInProcess(AUTH_ROUTES, [ "auth", "login", "--oauth", + "--client-id", + "override-client", + "--authorization-url", + "https://signin.example/oauth2/v1/auth", + "--dry-run", "--output", "json", ]); - expect(result.exitCode).toBe(2); - expect(result.stdout).toBe(""); - expect(result.stderr).toContain("--authorization-url"); - expect(result.stderr).not.toContain("--modelstudio-host"); - expect(result.stderr).not.toContain("--console-gateway"); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + plan: { client_id: string; authorization_url: string }; + missing: string[]; + }>(result.stdout); + expect(data.plan.client_id).toBe("override-client"); + expect(data.plan.authorization_url).toBe("https://signin.example/oauth2/v1/auth"); + expect(data.missing).toEqual([]); }); test("auth login --help 正常退出", async () => { @@ -192,7 +204,7 @@ describe("e2e: auth", () => { expect(data.plan.console_gateway).toBe("https://modelstudio-cs.console.aliyun.com"); }); - test("国际站线上 OAuth 未开放:--oauth --console-site international 阻断", async () => { + test("国际站线上 OAuth:--oauth --console-site international dry-run 给出内置线上端点", async () => { const result = await runCommandInProcess( AUTH_ROUTES, [ @@ -207,10 +219,27 @@ describe("e2e: auth", () => { ], { BAILIAN_PRE: "0" }, ); - expect(result.exitCode).toBe(2); - expect(result.stdout).toBe(""); - expect(result.stderr).toContain("International production OAuth login is not available yet"); - expect(result.stderr).toContain("国际站线上 OAuth 登录尚未开放"); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + plan: { + client_id: string; + console_region: string; + console_site: string; + authorization_url: string; + oauth_base_url: string; + modelstudio_host: string; + console_gateway: string; + }; + missing: string[]; + }>(result.stdout); + expect(data.plan.client_id).toBe("4102369295402391842"); + expect(data.plan.console_region).toBe("ap-southeast-1"); + expect(data.plan.console_site).toBe("international"); + expect(data.plan.authorization_url).toBe("https://signin.alibabacloud.com/oauth2/v1/auth"); + expect(data.plan.oauth_base_url).toBe("https://oauth.alibabacloud.com"); + expect(data.plan.modelstudio_host).toBe("modelstudio.ap-southeast-1.aliyuncs.com"); + expect(data.plan.console_gateway).toBe("https://bailian-singapore-cs.alibabacloud.com"); + expect(data.missing).toEqual([]); }); test("国际预发:缺网关 live 阻断,dry-run 离线列出缺失项,配齐网关后 missing 为空", async () => { diff --git a/packages/core/src/auth/aliyun-config.ts b/packages/core/src/auth/aliyun-config.ts index 528af97a3..8d2e05dfb 100644 --- a/packages/core/src/auth/aliyun-config.ts +++ b/packages/core/src/auth/aliyun-config.ts @@ -2,9 +2,14 @@ import { UsageError } from "../errors/base.ts"; import type { AliyunOAuthProfile } from "./aliyun-types.ts"; import type { ConsoleSite } from "../console/gateway.ts"; +// The IAM applications are promoted pre-release → online, so both stages share one client ID per site. export const ALIYUN_CLI_CLIENT_ID = "4001958595402383681"; +export const INTL_ALIYUN_CLI_CLIENT_ID = "4102369295402391842"; export const ALIYUN_CLI_SCOPE = "openid /internal/bailian/cli"; export const ALIYUN_OAUTH_BASE_URL = "https://oauth.aliyun.com"; +export const INTL_ALIYUN_OAUTH_BASE_URL = "https://oauth.alibabacloud.com"; +export const ALIYUN_AUTHORIZATION_URL = "https://signin.aliyun.com/oauth2/v1/auth"; +export const INTL_ALIYUN_AUTHORIZATION_URL = "https://signin.alibabacloud.com/oauth2/v1/auth"; /** Profiles saved before international support carry no console_site; they are domestic. */ export function profileSite(profile: Pick): ConsoleSite { diff --git a/packages/core/src/auth/index.ts b/packages/core/src/auth/index.ts index 4030a82f7..ed6136a1b 100644 --- a/packages/core/src/auth/index.ts +++ b/packages/core/src/auth/index.ts @@ -19,8 +19,12 @@ export { export { createOAuthSecretStore, type OAuthSecretStore } from "./secure-store.ts"; export { ALIYUN_CLI_CLIENT_ID, + INTL_ALIYUN_CLI_CLIENT_ID, ALIYUN_CLI_SCOPE, ALIYUN_OAUTH_BASE_URL, + INTL_ALIYUN_OAUTH_BASE_URL, + ALIYUN_AUTHORIZATION_URL, + INTL_ALIYUN_AUTHORIZATION_URL, normalizeOAuthUrl, normalizeOpenApiHost, parseAliyunOAuthProfile, diff --git a/packages/core/src/config/control-plane.ts b/packages/core/src/config/control-plane.ts index 0d6d7d45d..7d041d89d 100644 --- a/packages/core/src/config/control-plane.ts +++ b/packages/core/src/config/control-plane.ts @@ -1,4 +1,8 @@ -import { normalizeOAuthUrl, profileSite } from "../auth/aliyun-config.ts"; +import { + INTL_ALIYUN_CLI_CLIENT_ID, + normalizeOAuthUrl, + profileSite, +} from "../auth/aliyun-config.ts"; import type { AliyunOAuthProfile } from "../auth/aliyun-types.ts"; import { UsageError } from "../errors/base.ts"; @@ -28,7 +32,7 @@ const PRE_INTL_CONSOLE_ORIGIN: string | undefined = const PRE_INTL_CONSOLE_GATEWAY: string | undefined = "https://pre-bailian-singapore-cs.alibabacloud.com"; -export const PRE_INTL_ALIYUN_CLI_CLIENT_ID = "4102369295402391842"; +export const PRE_INTL_ALIYUN_CLI_CLIENT_ID = INTL_ALIYUN_CLI_CLIENT_ID; interface PreSiteGroup { region: string; diff --git a/skills/bailian-cli/reference/auth.md b/skills/bailian-cli/reference/auth.md index 5129cbe15..14180d5f2 100644 --- a/skills/bailian-cli/reference/auth.md +++ b/skills/bailian-cli/reference/auth.md @@ -65,10 +65,10 @@ bl auth generate-access-token --access-key-id LTAIxxxxx --access-key-secret xxxx | `--console-site ` | string | no | Console site: domestic, international | | `--open-api` | switch | no | Open the AccessKey setup guide, or save keys when --access-key-id and --access-key-secret are both set | | `--oauth` | switch | no | Sign in with Aliyun OAuth (domestic by default; use --console-site international for the international site). Exchanges a console session with automatic renewal | -| `--client-id ` | string | no | OAuth client ID; required for the first login outside pre-release | +| `--client-id ` | string | no | OAuth client ID override (built-in default per site) | | `--scope ` | string | no | OAuth scope (default: openid /internal/bailian/cli) | -| `--oauth-base-url ` | string | no | OAuth token service origin (production default: https://oauth.aliyun.com) | -| `--authorization-url ` | string | no | Explicit authorization URL; required for the first login outside pre-release | +| `--oauth-base-url ` | string | no | OAuth token service origin (default: https://oauth.aliyun.com; international: https://oauth.alibabacloud.com) | +| `--authorization-url ` | string | no | Authorization URL override (built-in default per site) | | `--modelstudio-host ` | string | no | Model Studio POP hostname override (domestic production default: modelstudio.cn-beijing.aliyuncs.com) | | `--console-gateway ` | string | no | Console gateway origin override (domestic production default: https://bailian-cs.console.aliyun.com) | | `--bailiancontrol-host ` | string | no | Optional Bailian Control OpenAPI hostname |