@autocodeflow/cli 1.7.0 → 1.9.0

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,40 +1,84 @@
1
1
  import { Command } from 'commander';
2
2
  import * as readline from 'readline';
3
- import { post, formatApiError } from '../client.js';
3
+ import { post, resetClient } from '../client.js';
4
4
  import { setApiUrl, setToken, setRefreshToken, showConfig } from '../config.js';
5
- import { resetClient } from '../client.js';
5
+ import { emitError, interruptExit, UsageError } from '../ui.js';
6
6
  import chalk from 'chalk';
7
7
  function prompt(question) {
8
8
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
9
+ // readline 终端模式(raw mode)下 Ctrl+C 不产生进程级 SIGINT 信号,而是触发
10
+ // rl 的 'SIGINT' 事件;若无监听,readline 只是 pause,login 会假死不退。
11
+ // 这里显式接住,与全局中断出口同码(130)。
12
+ rl.on('SIGINT', () => interruptExit());
9
13
  return new Promise((resolve) => rl.question(question, (ans) => { rl.close(); resolve(ans); }));
10
14
  }
11
15
  // PK-27(DEEP_REVIEW 0ef3bbe):交互式密码输入必须隐藏回显(否则旁窥/录屏即泄漏)。
12
16
  // 用 readline 的 _writeToOutput 覆盖把回显吞掉——这是 Node 生态隐藏密码的标准做法,
13
17
  // 不引入额外依赖。TTY 非交互(CI/管道)时退化为普通 question(无回显需求,因为
14
18
  // 此时密码应来自 --password 或 ACF_PASSWORD env,而非人工键入)。
19
+ //
20
+ // UX 打磨(本轮):遮蔽逻辑抽成独立函数并导出——「密码不回显」是安全语义,
21
+ // 值得一个函数级不回显断言(ux-uniform.test.ts),内联在闭包里则测不到。
22
+ export function maskEcho(rl, isTTY = process.stdin.isTTY === true) {
23
+ if (!isTTY)
24
+ return;
25
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
+ const rlAny = rl;
27
+ const out = rlAny.output;
28
+ rlAny._writeToOutput = (str) => {
29
+ // 只回显提示符的换行,不回显键入字符;退格/回车照常处理。
30
+ if (str === '\n')
31
+ out.write('\n');
32
+ else if (str === '\r')
33
+ out.write('\n');
34
+ else
35
+ out.write('');
36
+ return '';
37
+ };
38
+ }
15
39
  function hiddenPrompt(question) {
16
40
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
17
- if (process.stdin.isTTY) {
18
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
- const rlAny = rl;
20
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
- const out = rlAny.output;
22
- rlAny._writeToOutput = (str) => {
23
- // 只回显提示符的换行,不回显键入字符;退格/回车照常处理。
24
- if (str === '\n')
25
- out.write('\n');
26
- else if (str === '\r')
27
- out.write('\n');
28
- else
29
- out.write('');
30
- return '';
31
- };
32
- }
41
+ // 同上:raw 模式 Ctrl+C 显式接住,避免密码输入中 Ctrl+C 假死。
42
+ rl.on('SIGINT', () => interruptExit());
43
+ maskEcho(rl);
33
44
  return new Promise((resolve) => rl.question(question, (ans) => {
34
45
  rl.close();
35
46
  resolve(ans);
36
47
  }));
37
48
  }
49
+ // 6 位码形态校验(TOTP 契约:HMAC-SHA1/6 位数字)。本地只判「形态」,
50
+ // 码对不对由服务端 /auth/totp/verify 判(错码 → 401 → 退出码 3)。
51
+ function assertTotpCodeFormat(code, source) {
52
+ if (!/^\d{6}$/.test(code)) {
53
+ const label = source === '--code' ? '--code' : 'Expected';
54
+ throw new UsageError(source === '--code'
55
+ ? `${label} must be a 6-digit TOTP code (got "${code}")`
56
+ : `${label} a 6-digit TOTP code (got "${code}")`);
57
+ }
58
+ }
59
+ // SEC-03:TOTP 登录第二段的 6 位码获取。
60
+ // - --code 提供 → 直接使用(CI/非交互场景,不碰 stdin);
61
+ // - 未提供且 stdin 非交互(TTY 检测,与 maskEcho 同判据)→ 可操作报错
62
+ // (UsageError → 退出码 2),明示如何用 --code 完成;
63
+ // - 其余 → 交互式 prompt(6 位码是一次性短效凭证,不需要像密码那样遮蔽回显)。
64
+ // 本地形态错误一律 throw UsageError(而非 emitUsageError):调用方 login 的
65
+ // action 在 try/catch 里统一走 emitError 出口,UsageError 会被映射到退出码 2
66
+ //(与 task create --file 的本地 payload 错误同一套路)。
67
+ // 导出供单测注入 promptFn(TTY 交互路径无法在测试里驱动真实 stdin)。
68
+ export async function resolveTotpCode(opts, promptFn = prompt) {
69
+ if (opts.code) {
70
+ const code = opts.code.trim();
71
+ assertTotpCodeFormat(code, '--code');
72
+ return code;
73
+ }
74
+ if (process.stdin.isTTY !== true) {
75
+ throw new UsageError('This account has TOTP enabled and stdin is not interactive (no prompt can be shown). ' +
76
+ 'Pass the 6-digit code with --code <code>, e.g. acf login --user admin --code 123456.');
77
+ }
78
+ const code = (await promptFn('TOTP code (6 digits): ')).trim();
79
+ assertTotpCodeFormat(code, 'prompt');
80
+ return code;
81
+ }
38
82
  export function loginCommand() {
39
83
  const cmd = new Command('login')
40
84
  .description('Authenticate with the AutoCodeFlow API and save credentials')
@@ -43,6 +87,9 @@ export function loginCommand() {
43
87
  // PK-27(DEEP_REVIEW 0ef3bbe):--password 明文会进 ps/shell history,标记 deprecated。
44
88
  // 仍保留以便一次性容器/CI 用(此时 ACF_PASSWORD env 更推荐,不进进程 argv)。
45
89
  .option('--password <password>', 'Password (DEPRECATED: visible in process list & shell history; prefer interactive hidden prompt or ACF_PASSWORD env)')
90
+ // SEC-03:TOTP 二段登录的 6 位动态码。交互终端下可省略(会 prompt);
91
+ // CI/非交互场景必须提供(stdin 非 TTY 且无 --code 时直接报用法错误)。
92
+ .option('--code <code>', '6-digit TOTP code (second factor). Required in non-interactive sessions when the account has TOTP enabled')
46
93
  .action(async (opts) => {
47
94
  try {
48
95
  const url = opts.url || await prompt('API URL [http://localhost:3105]: ') || 'http://localhost:3105';
@@ -61,25 +108,47 @@ export function loginCommand() {
61
108
  else {
62
109
  password = await hiddenPrompt('Password: ');
63
110
  }
64
- // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }
111
+ // --code 形态本地预检(在发起任何网络请求之前):坏格式直接报用法错误,
112
+ // 不消耗服务端登录限流(login 20/min、totp/verify 10/min 都是稀缺预算)。
113
+ if (opts.code)
114
+ assertTotpCodeFormat(String(opts.code).trim(), '--code');
115
+ // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }.
116
+ // SEC-03: TOTP 已启用用户返回 200 + { totpRequired: true }(无 token),
117
+ // 进入二段流程:username+password+code 复验后签发双 token。
65
118
  const data = await post('/auth/login', {
66
119
  username: username.trim(),
67
120
  password,
68
121
  });
69
- if (!data.accessToken) {
122
+ let tokens;
123
+ if ('accessToken' in data && data.accessToken) {
124
+ tokens = data;
125
+ }
126
+ else if (data.totpRequired === true) {
127
+ const code = await resolveTotpCode(opts);
128
+ // 契约(api-reference.md / TotpVerifyDto):{ username, password, code },
129
+ // 响应与普通登录同形(双 token)。错码 → 401(计入登录失败锁定),
130
+ // 走下方统一的 Login failed 错误出口(退出码 3)。
131
+ tokens = await post('/auth/totp/verify', {
132
+ username: username.trim(),
133
+ password,
134
+ code,
135
+ });
136
+ }
137
+ else {
70
138
  throw new Error('Login response missing accessToken (unexpected auth payload)');
71
139
  }
72
- setToken(data.accessToken);
140
+ setToken(tokens.accessToken);
73
141
  // BUG-13: refreshToken 一并入库——access token 默认 15m 过期,
74
142
  // client 的 401 单飞自愈(/auth/refresh + 重放一次)依赖它,
75
143
  // 否则过期后全命令 401 只能重新 login。
76
- setRefreshToken(data.refreshToken ?? '');
144
+ setRefreshToken(tokens.refreshToken ?? '');
77
145
  console.log(chalk.green('✔ Logged in successfully'));
78
146
  showConfig();
79
147
  }
80
148
  catch (e) {
81
- console.error(chalk.red('✗ Login failed:'), formatApiError(e));
82
- process.exit(1);
149
+ // 统一错误出口:401(密码错/TOTP 码错/token 失效)→ 退出码 3,
150
+ // 网络不通 → 4,其余 → 1(见 ui.ts 的 EXIT_CODES 表)。
151
+ emitError('Login failed', e);
83
152
  }
84
153
  });
85
154
  return cmd;
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, formatApiError } from '../client.js';
5
+ import { get } from '../client.js';
6
+ import { emitError } from '../ui.js';
6
7
  const ROLE_COLOR = {
7
8
  admin: chalk.yellow,
8
9
  editor: chalk.cyan,
@@ -50,9 +51,7 @@ export function projectsCommand() {
50
51
  console.log(table.toString());
51
52
  }
52
53
  catch (e) {
53
- spinner.stop();
54
- console.error(chalk.red(formatApiError(e)));
55
- process.exitCode = 1;
54
+ emitError('Failed to list projects', e, { spinner });
56
55
  }
57
56
  });
58
57
  cmd
@@ -81,9 +80,7 @@ export function projectsCommand() {
81
80
  console.log(table.toString());
82
81
  }
83
82
  catch (e) {
84
- spinner.stop();
85
- console.error(chalk.red(formatApiError(e)));
86
- process.exitCode = 1;
83
+ emitError('Failed to list members', e, { spinner });
87
84
  }
88
85
  });
89
86
  return cmd;
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, formatApiError } from '../client.js';
5
+ import { get } from '../client.js';
6
+ import { emitError } from '../ui.js';
6
7
  export function sopCommand() {
7
8
  const cmd = new Command('sop').description('Inspect SOP definitions');
8
9
  // acf sop list
@@ -11,6 +12,8 @@ export function sopCommand() {
11
12
  .option('--status <status>', 'Filter by SOP status (draft | published | deprecated)')
12
13
  .option('-p, --page <n>', 'Page number', '1')
13
14
  .option('-n, --page-size <n>', 'Page size (max 100)', '20')
15
+ // --json 补面(本轮 UX 统一):对齐 audit list 的信封直出口径
16
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
14
17
  .action(async (opts) => {
15
18
  const spinner = ora('Fetching SOPs…').start();
16
19
  try {
@@ -20,6 +23,10 @@ export function sopCommand() {
20
23
  status: opts.status,
21
24
  });
22
25
  spinner.stop();
26
+ if (opts.json) {
27
+ console.log(JSON.stringify(data));
28
+ return;
29
+ }
23
30
  const items = data.items ?? [];
24
31
  const table = new Table({
25
32
  head: ['Title', 'Slug', 'Status', 'Version', 'Updated'],
@@ -39,19 +46,23 @@ export function sopCommand() {
39
46
  console.log(chalk.gray(`Total: ${data.total ?? items.length} page ${opts.page}`));
40
47
  }
41
48
  catch (e) {
42
- spinner.fail('Failed to list SOPs');
43
- console.error(chalk.red(formatApiError(e)));
44
- process.exit(1);
49
+ emitError('Failed to list SOPs', e, { spinner });
45
50
  }
46
51
  });
47
52
  // acf sop show <id>
48
53
  cmd.command('show <sopId>')
49
54
  .description('Show one SOP: status, current version and markdown body')
50
- .action(async (sopId) => {
55
+ // --json 补面(本轮 UX 统一):单对象形态 → pretty JSON
56
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
57
+ .action(async (sopId, opts) => {
51
58
  const spinner = ora('Fetching SOP…').start();
52
59
  try {
53
60
  const s = await get(`/sop/${sopId}`);
54
61
  spinner.stop();
62
+ if (opts.json) {
63
+ console.log(JSON.stringify(s, null, 2));
64
+ return;
65
+ }
55
66
  console.log(chalk.bold(s.title));
56
67
  console.log(chalk.gray(`slug: ${s.slug} status: ${s.status} version: ${s.currentVersion ?? '-'} updated: ${s.updatedAt ?? '-'}`));
57
68
  if (s.bodyMarkdown) {
@@ -63,9 +74,7 @@ export function sopCommand() {
63
74
  }
64
75
  }
65
76
  catch (e) {
66
- spinner.fail('Failed to show SOP');
67
- console.error(chalk.red(formatApiError(e)));
68
- process.exit(1);
77
+ emitError('Failed to show SOP', e, { spinner });
69
78
  }
70
79
  });
71
80
  return cmd;
@@ -1,2 +1,8 @@
1
1
  import { Command } from 'commander';
2
+ /**
3
+ * E-1:`acf task import -` 的 stdin 读取。"-" 是 CI/管道惯例;stdin 是 TTY
4
+ * 时(用户忘了给文件、手敲 `-`)拒绝而不是挂死等待 EOF。流参数可注入——
5
+ * 单测用 PassThrough 驱动,不碰真实 stdin。
6
+ */
7
+ export declare function readStdin(stream?: NodeJS.ReadableStream): Promise<string>;
2
8
  export declare function tasksCommand(): Command;