@autocodeflow/cli 1.8.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,10 @@
1
1
  import { Command } from 'commander';
2
2
  import * as readline from 'readline';
3
- import { post, resetClient } from '../client.js';
4
- import { setApiUrl, setToken, setRefreshToken, showConfig } from '../config.js';
5
- import { emitError, interruptExit } from '../ui.js';
3
+ import ora from 'ora';
4
+ import axios from 'axios';
5
+ import { post, get, resetClient } from '../client.js';
6
+ import { setApiUrl, setToken, setRefreshToken, showConfig, getApiUrl, clearAuth } from '../config.js';
7
+ import { emitError, interruptExit, UsageError } from '../ui.js';
6
8
  import chalk from 'chalk';
7
9
  function prompt(question) {
8
10
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -36,6 +38,10 @@ export function maskEcho(rl, isTTY = process.stdin.isTTY === true) {
36
38
  return '';
37
39
  };
38
40
  }
41
+ /**
42
+ * 交互式密码输入(回显遮蔽)。非交互路径不再走这里——由 promptOrFail 在
43
+ * 更外层拦下并提示改用 ACF_PASSWORD(见 login action 的 password 分支)。
44
+ */
39
45
  function hiddenPrompt(question) {
40
46
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
41
47
  // 同上:raw 模式 Ctrl+C 显式接住,避免密码输入中 Ctrl+C 假死。
@@ -46,6 +52,67 @@ function hiddenPrompt(question) {
46
52
  resolve(ans);
47
53
  }));
48
54
  }
55
+ /**
56
+ * P0(CLI-AGENT-UX-AUDIT):登录地址解析的单一事实源(导出供单测)。
57
+ *
58
+ * 优先级:显式 `--url` > `ACF_API_URL` env > 已存配置 > 内置默认值。
59
+ * 前两者与磁盘配置都由 getApiUrl() 归一(其自身就是 env || store),
60
+ * 因此这里只需在「显式 --url」与「其余」之间分流。
61
+ *
62
+ * 关键点:**不再对地址发交互 prompt**。地址有合理默认值,为它中断整条登录
63
+ * 在自动化面只会制造困惑(旧行为下 agent 会拿到空串兜底的默认地址 + 假 exit 0)。
64
+ */
65
+ export function resolveLoginUrl(explicit) {
66
+ return explicit?.trim() || getApiUrl() || 'http://localhost:3105';
67
+ }
68
+ /**
69
+ * P0(CLI-AGENT-UX-AUDIT):非交互下需要人工输入时给出**可操作**的用法错误,
70
+ * 而不是让 prompt 拿到 EOF 空串后静默继续。契约与 resolveTotpCode 的
71
+ * 「stdin 非交互且缺 --code」分支完全一致(UsageError → 退出码 2)。
72
+ *
73
+ * @param question 交互提示语
74
+ * @param alternative 非交互时应改用的旗标/环境变量(写进错误消息)
75
+ */
76
+ export async function promptOrFail(question, alternative, promptFn = prompt) {
77
+ if (process.stdin.isTTY !== true) {
78
+ throw new UsageError(`Cannot prompt for "${question.trim()}" — stdin is not interactive. ` +
79
+ `Provide it with ${alternative} instead (required for CI / agent use).`);
80
+ }
81
+ return promptFn(question);
82
+ }
83
+ // 6 位码形态校验(TOTP 契约:HMAC-SHA1/6 位数字)。本地只判「形态」,
84
+ // 码对不对由服务端 /auth/totp/verify 判(错码 → 401 → 退出码 3)。
85
+ function assertTotpCodeFormat(code, source) {
86
+ if (!/^\d{6}$/.test(code)) {
87
+ const label = source === '--code' ? '--code' : 'Expected';
88
+ throw new UsageError(source === '--code'
89
+ ? `${label} must be a 6-digit TOTP code (got "${code}")`
90
+ : `${label} a 6-digit TOTP code (got "${code}")`);
91
+ }
92
+ }
93
+ // SEC-03:TOTP 登录第二段的 6 位码获取。
94
+ // - --code 提供 → 直接使用(CI/非交互场景,不碰 stdin);
95
+ // - 未提供且 stdin 非交互(TTY 检测,与 maskEcho 同判据)→ 可操作报错
96
+ // (UsageError → 退出码 2),明示如何用 --code 完成;
97
+ // - 其余 → 交互式 prompt(6 位码是一次性短效凭证,不需要像密码那样遮蔽回显)。
98
+ // 本地形态错误一律 throw UsageError(而非 emitUsageError):调用方 login 的
99
+ // action 在 try/catch 里统一走 emitError 出口,UsageError 会被映射到退出码 2
100
+ //(与 task create --file 的本地 payload 错误同一套路)。
101
+ // 导出供单测注入 promptFn(TTY 交互路径无法在测试里驱动真实 stdin)。
102
+ export async function resolveTotpCode(opts, promptFn = prompt) {
103
+ if (opts.code) {
104
+ const code = opts.code.trim();
105
+ assertTotpCodeFormat(code, '--code');
106
+ return code;
107
+ }
108
+ if (process.stdin.isTTY !== true) {
109
+ throw new UsageError('This account has TOTP enabled and stdin is not interactive (no prompt can be shown). ' +
110
+ 'Pass the 6-digit code with --code <code>, e.g. acf login --user admin --code 123456.');
111
+ }
112
+ const code = (await promptFn('TOTP code (6 digits): ')).trim();
113
+ assertTotpCodeFormat(code, 'prompt');
114
+ return code;
115
+ }
49
116
  export function loginCommand() {
50
117
  const cmd = new Command('login')
51
118
  .description('Authenticate with the AutoCodeFlow API and save credentials')
@@ -54,45 +121,169 @@ export function loginCommand() {
54
121
  // PK-27(DEEP_REVIEW 0ef3bbe):--password 明文会进 ps/shell history,标记 deprecated。
55
122
  // 仍保留以便一次性容器/CI 用(此时 ACF_PASSWORD env 更推荐,不进进程 argv)。
56
123
  .option('--password <password>', 'Password (DEPRECATED: visible in process list & shell history; prefer interactive hidden prompt or ACF_PASSWORD env)')
124
+ // SEC-03:TOTP 二段登录的 6 位动态码。交互终端下可省略(会 prompt);
125
+ // CI/非交互场景必须提供(stdin 非 TTY 且无 --code 时直接报用法错误)。
126
+ .option('--code <code>', '6-digit TOTP code (second factor). Required in non-interactive sessions when the account has TOTP enabled')
57
127
  .action(async (opts) => {
58
128
  try {
59
- const url = opts.url || await prompt('API URL [http://localhost:3105]: ') || 'http://localhost:3105';
129
+ // P0(CLI-AGENT-UX-AUDIT):URL 解析优先级此前是 `--url || prompt`——
130
+ // 只要没传 --url 就一定发问,即便 ACF_API_URL / 磁盘配置已经给了地址。
131
+ // stdin 非交互(agent / CI / `< NUL`)时 prompt 拿到空串、被
132
+ // `|| 'http://localhost:3105'` 兜底,后续 username/password 同样问不出来,
133
+ // 进程在某个 prompt 处静默 exit 0——**agent 以为自己登录成功了**,而
134
+ // 落盘的 token 是空的,错误被推迟到下一个命令的 401 才暴露。
135
+ //
136
+ // 收敛为纯函数(可单测):显式 --url > ACF_API_URL > 已存配置 > 默认值。
137
+ // 只有四者都拿不到「非默认」地址、且 stdin 是 TTY 时才会问人;非 TTY
138
+ // 一律用默认值继续(地址本就有合理默认,不该因为它中断整条登录)。
139
+ const url = resolveLoginUrl(opts.url);
60
140
  setApiUrl(url.trim());
61
141
  resetClient();
62
- const username = opts.user || await prompt('Username: ');
142
+ // 非交互下 username 无法发问:此时必须由 --user 提供,否则可操作报错
143
+ // (与 TOTP 的 --code 同款契约),不再静默拿到空用户名。
144
+ const username = opts.user || (await promptOrFail('Username: ', '--user <username>'));
63
145
  // PK-27 凭据来源优先级:--password(deprecated,告警) > ACF_PASSWORD env > 隐藏交互 prompt。
64
146
  let password;
65
147
  if (opts.password) {
66
- process.stderr.write(chalk.yellow('⚠ --password 会出现在进程列表与 shell 历史中;CI 场景请改用 ACF_PASSWORD 环境变量。\n'));
148
+ process.stderr.write(chalk.yellow('⚠ --password is visible in the process list and shell history — prefer ACF_PASSWORD env in CI.\n'));
67
149
  password = opts.password;
68
150
  }
69
151
  else if (process.env.ACF_PASSWORD) {
70
152
  password = process.env.ACF_PASSWORD;
71
153
  }
72
154
  else {
155
+ // 非交互下必须走 ACF_PASSWORD env(不进 argv、不落 shell history),
156
+ // 不能退化成「问不出来就空密码发一次必然 401 的请求」。
157
+ // 交互路径继续用 hiddenPrompt —— PK-27 的回显遮蔽不能因这次改造丢掉。
158
+ if (process.stdin.isTTY !== true) {
159
+ throw new UsageError('Cannot prompt for the password — stdin is not interactive. ' +
160
+ 'Provide it with the ACF_PASSWORD environment variable instead (required for CI / agent use).');
161
+ }
73
162
  password = await hiddenPrompt('Password: ');
74
163
  }
75
- // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }
164
+ // --code 形态本地预检(在发起任何网络请求之前):坏格式直接报用法错误,
165
+ // 不消耗服务端登录限流(login 20/min、totp/verify 10/min 都是稀缺预算)。
166
+ if (opts.code)
167
+ assertTotpCodeFormat(String(opts.code).trim(), '--code');
168
+ // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }.
169
+ // SEC-03: TOTP 已启用用户返回 200 + { totpRequired: true }(无 token),
170
+ // 进入二段流程:username+password+code 复验后签发双 token。
76
171
  const data = await post('/auth/login', {
77
172
  username: username.trim(),
78
173
  password,
79
174
  });
80
- if (!data.accessToken) {
175
+ let tokens;
176
+ if ('accessToken' in data && data.accessToken) {
177
+ tokens = data;
178
+ }
179
+ else if (data.totpRequired === true) {
180
+ const code = await resolveTotpCode(opts);
181
+ // 契约(api-reference.md / TotpVerifyDto):{ username, password, code },
182
+ // 响应与普通登录同形(双 token)。错码 → 401(计入登录失败锁定),
183
+ // 走下方统一的 Login failed 错误出口(退出码 3)。
184
+ tokens = await post('/auth/totp/verify', {
185
+ username: username.trim(),
186
+ password,
187
+ code,
188
+ });
189
+ }
190
+ else {
81
191
  throw new Error('Login response missing accessToken (unexpected auth payload)');
82
192
  }
83
- setToken(data.accessToken);
193
+ setToken(tokens.accessToken);
84
194
  // BUG-13: refreshToken 一并入库——access token 默认 15m 过期,
85
195
  // client 的 401 单飞自愈(/auth/refresh + 重放一次)依赖它,
86
196
  // 否则过期后全命令 401 只能重新 login。
87
- setRefreshToken(data.refreshToken ?? '');
197
+ setRefreshToken(tokens.refreshToken ?? '');
88
198
  console.log(chalk.green('✔ Logged in successfully'));
89
199
  showConfig();
90
200
  }
91
201
  catch (e) {
92
- // 统一错误出口:401(密码错/token 失效)→ 退出码 3,网络不通 → 4,
93
- // 其余 → 1(见 ui.ts 的 EXIT_CODES 表)。
202
+ // 统一错误出口:401(密码错/TOTP 码错/token 失效)→ 退出码 3,
203
+ // 网络不通 → 4,其余 → 1(见 ui.ts 的 EXIT_CODES 表)。
94
204
  emitError('Login failed', e);
95
205
  }
96
206
  });
97
207
  return cmd;
98
208
  }
209
+ /**
210
+ * P1(CLI-AGENT-UX-AUDIT):`acf whoami` —— 打印当前凭据的身份与角色。
211
+ *
212
+ * 为什么 agent 需要它:后端有大量 ADMIN-only 面(audit / sop / notification /
213
+ * agent / executor-packages 全模块,以及所有应用写操作)。此前 agent 无法在
214
+ * 开工前自检权限,只能靠「调用 → 403」逐个试错。profile 返回的是 AuthUser,
215
+ * 其中 `role` 是**单值**(不是 roles 数组),ADMIN 判定按此单值。
216
+ */
217
+ export function whoamiCommand() {
218
+ return new Command('whoami')
219
+ .description('Show the identity and role behind the current credential (preflight before ADMIN-only commands)')
220
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
221
+ .action(async (opts) => {
222
+ const spinner = ora('Fetching profile…').start();
223
+ try {
224
+ const me = await get('/auth/profile');
225
+ spinner.stop();
226
+ if (opts.json) {
227
+ console.log(JSON.stringify(me, null, 2));
228
+ return;
229
+ }
230
+ const isAdmin = me?.role === 'admin' || me?.role === 'ADMIN';
231
+ console.log(chalk.bold('Current identity'));
232
+ console.log(' Username :', me?.username ?? '-');
233
+ console.log(' User ID :', me?.id ?? '-');
234
+ console.log(' Role :', isAdmin ? chalk.yellow(me?.role) : (me?.role ?? '-'));
235
+ console.log(' Email :', me?.email ?? '-');
236
+ console.log(' API URL :', getApiUrl());
237
+ if (!isAdmin) {
238
+ console.log(chalk.gray(' (not an ADMIN — audit / sop / notification / agent / executor-packages and application writes will answer 403)'));
239
+ }
240
+ }
241
+ catch (e) {
242
+ emitError('Failed to fetch profile', e, { spinner });
243
+ }
244
+ });
245
+ }
246
+ /**
247
+ * P1(CLI-AGENT-UX-AUDIT):`acf logout` —— 服务端吊销 refresh token 家族的
248
+ * 同时清空本地凭据。
249
+ *
250
+ * 为什么 agent 需要它:access + refresh **双 token** 都落在磁盘 0600 文件里,
251
+ * refresh 是长效的。共享机器 / 一次性容器上跑完不清,等于把一枚长效凭证留在
252
+ * 盘上。此前面只有「再 login 一次覆盖」,没有出口。
253
+ *
254
+ * 语义:先尽力通知服务端(revoke all refresh tokens),**网络失败也照常清本地**
255
+ * ——本地凭据必须确保被抹掉,不能因为服务端不可达就把 token 留在盘上。
256
+ */
257
+ export function logoutCommand() {
258
+ return new Command('logout')
259
+ .description('Revoke the session server-side and clear the locally stored credentials')
260
+ .action(async () => {
261
+ // ⚠ 顺序至关重要:client 的请求拦截器是**逐请求**读 token 的
262
+ //(client.ts request interceptor → getToken()),所以必须先带着 token
263
+ // 完成服务端吊销,**再**清本地。反过来(先 clearAuth 再 POST)会让注销
264
+ // 请求不带 Authorization 头 → 必然 401 → 服务端吊销实际从未发生。
265
+ let warned = false;
266
+ try {
267
+ // POST /auth/logout —— 吊销该用户的全部 refresh token(服务端语义)。
268
+ await post('/auth/logout');
269
+ }
270
+ catch (e) {
271
+ // 401 = 本来就没登录 / token 已失效,没有可吊销的会话,属正常收尾,
272
+ // 不打扰用户。其余(网络不可达 / 5xx)才值得告警——注意此时本地凭据
273
+ // **仍然会被清掉**(下方 finally),不能因为服务端不可达就把 token 留盘。
274
+ const status = axios.isAxiosError(e) ? e.response?.status : undefined;
275
+ if (status !== 401) {
276
+ warned = true;
277
+ process.stderr.write(chalk.yellow('⚠ Could not reach the API to revoke the session server-side (the access token may remain valid until it expires) — local credentials were still cleared.\n'));
278
+ }
279
+ }
280
+ finally {
281
+ // 无论服务端结果如何,盘上的凭据都必须抹掉。
282
+ clearAuth();
283
+ }
284
+ if (!warned)
285
+ console.log(chalk.green('✔ Logged out — local credentials cleared'));
286
+ else
287
+ console.log(chalk.green('✔ Local credentials cleared'));
288
+ });
289
+ }
@@ -1,2 +1,18 @@
1
1
  import { Command } from 'commander';
2
+ /**
3
+ * 结构化失败原因(failureReason,执行器回调上报)→ 可直接照做的建议。
4
+ *
5
+ * 2026-10 开发人员实测:任务声明 runtimeVersion=3.12 派到无该解释器的执行器
6
+ * 秒失败且执行日志 0 行——failureReason=interpreter_unavailable 只有 --json
7
+ * 里能看到,中文详情还得再查一次文档。把最常见的几个失败原因翻译成"下一步
8
+ * 怎么做",随 `--wait` 的失败终态直接打出来(键集对齐 executor-node
9
+ * protocol.schemas.ts 的 CallbackFailureReason 枚举)。
10
+ */
11
+ export declare const FAILURE_REASON_HINTS: Record<string, string>;
12
+ /**
13
+ * E-1:`acf task import -` 的 stdin 读取。"-" 是 CI/管道惯例;stdin 是 TTY
14
+ * 时(用户忘了给文件、手敲 `-`)拒绝而不是挂死等待 EOF。流参数可注入——
15
+ * 单测用 PassThrough 驱动,不碰真实 stdin。
16
+ */
17
+ export declare function readStdin(stream?: NodeJS.ReadableStream): Promise<string>;
2
18
  export declare function tasksCommand(): Command;