@pikecode/api-key-manager 2.0.0 → 2.0.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.
Files changed (60) hide show
  1. package/README.md +444 -151
  2. package/bin/akm.js +340 -11
  3. package/package.json +29 -12
  4. package/src/CommandRegistry.js +58 -3
  5. package/src/commands/BaseCommand.js +68 -1
  6. package/src/commands/add/prompts.js +280 -0
  7. package/src/commands/add/providerSaver.js +74 -0
  8. package/src/commands/add/summaryPrinter.js +29 -0
  9. package/src/commands/add.js +54 -439
  10. package/src/commands/backup.js +396 -0
  11. package/src/commands/batch.js +313 -0
  12. package/src/commands/benchmark.js +323 -0
  13. package/src/commands/claude-clean.js +253 -0
  14. package/src/commands/clone.js +265 -0
  15. package/src/commands/current.js +89 -41
  16. package/src/commands/edit.js +3 -207
  17. package/src/commands/health.js +264 -0
  18. package/src/commands/list.js +120 -35
  19. package/src/commands/mcp.js +467 -0
  20. package/src/commands/remove.js +89 -26
  21. package/src/commands/stats.js +281 -0
  22. package/src/commands/switch/claude-settings-compatibility.js +113 -0
  23. package/src/commands/switch/launch-args-helper.js +84 -0
  24. package/src/commands/switch/provider-choices-helper.js +72 -0
  25. package/src/commands/switch/provider-details-helper.js +46 -0
  26. package/src/commands/switch/provider-edit-questions-helper.js +124 -0
  27. package/src/commands/switch/provider-launcher.js +20 -0
  28. package/src/commands/switch/provider-manager.js +214 -0
  29. package/src/commands/switch/status-helper.js +124 -0
  30. package/src/commands/switch/ui-screen-renderer.js +77 -0
  31. package/src/commands/switch.js +471 -958
  32. package/src/commands/validate.js +310 -0
  33. package/src/config.js +541 -55
  34. package/src/constants/index.js +234 -0
  35. package/src/constants/ui.js +108 -0
  36. package/src/index.js +11 -4
  37. package/src/navigation/EscNavigationManager.js +5 -5
  38. package/src/utils/atomic-file.js +47 -0
  39. package/src/utils/claude-settings.js +4 -4
  40. package/src/utils/codex-files.js +418 -0
  41. package/src/utils/codex-launcher.js +104 -0
  42. package/src/utils/concurrency.js +30 -0
  43. package/src/utils/config-opener.js +22 -2
  44. package/src/utils/env-launcher.js +50 -44
  45. package/src/utils/env-utils.js +52 -0
  46. package/src/utils/error-handler.js +27 -28
  47. package/src/utils/health-checker.js +350 -0
  48. package/src/utils/import-validator.js +210 -0
  49. package/src/utils/inquirer-setup.js +11 -0
  50. package/src/utils/launch-args.js +155 -0
  51. package/src/utils/logger.js +0 -1
  52. package/src/utils/provider-status-checker.js +211 -64
  53. package/src/utils/secrets.js +22 -0
  54. package/src/utils/shell-snippets.js +32 -0
  55. package/src/utils/terminal-format.js +22 -4
  56. package/src/utils/ui-helper.js +96 -86
  57. package/src/utils/update-checker.js +41 -12
  58. package/src/utils/validator.js +115 -88
  59. package/bin/cc.js +0 -101
  60. package/src/utils/storage.js +0 -55
@@ -1,38 +1,7 @@
1
1
  const chalk = require('chalk');
2
2
 
3
3
  class UIHelper {
4
- // 颜色主题
5
- static colors = {
6
- primary: chalk.cyan,
7
- secondary: chalk.blue,
8
- success: chalk.green,
9
- warning: chalk.yellow,
10
- error: chalk.red,
11
- info: chalk.white,
12
- muted: chalk.gray,
13
- accent: chalk.magenta
14
- };
15
-
16
- // 图标
17
- static icons = {
18
- success: '✅',
19
- error: '❌',
20
- warning: '⚠️',
21
- info: 'ℹ️',
22
- loading: '⏳',
23
- arrow: '→',
24
- back: '🔙',
25
- home: '🏠',
26
- settings: '⚙️',
27
- add: '➕',
28
- edit: '✏️',
29
- delete: '🗑️',
30
- launch: '🚀',
31
- list: '📋',
32
- config: '🛠️',
33
- current: '🎯',
34
- search: '🔍'
35
- };
4
+ // 创建标题
36
5
 
37
6
  // 创建标题
38
7
  static createTitle(text, icon = '') {
@@ -47,36 +16,37 @@ class UIHelper {
47
16
 
48
17
  // 创建项目列表
49
18
  static createItem(label, value, isSelected = false) {
50
- const icon = isSelected ? this.icons.current : '•';
51
- const color = isSelected ? this.colors.primary : this.colors.info;
19
+ const icon = isSelected ? UIHelper.icons.current : '•';
20
+ const color = isSelected ? UIHelper.colors.primary : UIHelper.colors.info;
52
21
  return `${color(icon)} ${label}`;
53
22
  }
54
23
 
55
24
  // 创建操作按钮
56
25
  static createButton(label, action, icon = '') {
57
26
  const fullIcon = icon ? `${icon} ` : '';
58
- return `${this.colors.accent(fullIcon)}${this.colors.info(label)}`;
27
+ return `${UIHelper.colors.accent(fullIcon)}${UIHelper.colors.info(label)}`;
59
28
  }
60
29
 
61
30
  // 创建状态指示器
62
31
  static createStatus(status, label) {
63
32
  const statusConfig = {
64
- current: { icon: this.icons.current, color: this.colors.success },
65
- active: { icon: '🟢', color: this.colors.success },
66
- inactive: { icon: '⚫', color: this.colors.muted },
67
- loading: { icon: this.icons.loading, color: this.colors.warning },
68
- error: { icon: this.icons.error, color: this.colors.error }
33
+ current: { icon: UIHelper.icons.current, color: UIHelper.colors.success },
34
+ active: { icon: chalk.green('●'), color: UIHelper.colors.success },
35
+ inactive: { icon: chalk.gray('·'), color: UIHelper.colors.muted },
36
+ loading: { icon: UIHelper.icons.loading, color: UIHelper.colors.warning },
37
+ error: { icon: UIHelper.icons.error, color: UIHelper.colors.error }
69
38
  };
70
39
 
71
40
  const config = statusConfig[status] || statusConfig.inactive;
72
- return `${config.color(config.icon)} ${this.colors.info(label)}`;
41
+ return `${config.color(config.icon)} ${UIHelper.colors.info(label)}`;
73
42
  }
74
43
 
75
44
  // 格式化供应商信息
76
45
  static formatProvider(provider) {
77
46
  const status = provider.current ? 'current' : 'inactive';
78
- const statusText = this.createStatus(status, provider.name);
79
- const displayName = this.colors.secondary(`(${provider.displayName})`);
47
+ const statusText = UIHelper.createStatus(status, provider.name);
48
+ const displayName = UIHelper.colors.secondary(`(${provider.displayName})`);
49
+
80
50
  return `${statusText} ${displayName}`;
81
51
  }
82
52
 
@@ -87,73 +57,80 @@ class UIHelper {
87
57
  const filled = '█'.repeat(progress);
88
58
  const emptySpace = '░'.repeat(empty);
89
59
  const percentage = Math.floor((current / total) * 100);
90
-
91
- return `${this.colors.primary(filled)}${this.colors.muted(emptySpace)} ${this.colors.info(percentage + '%')}`;
60
+
61
+ return `${UIHelper.colors.primary(filled)}${UIHelper.colors.muted(emptySpace)} ${UIHelper.colors.info(percentage + '%')}`;
92
62
  }
93
63
 
94
64
  // 创建表格
95
65
  static createTable(headers, rows) {
96
66
  const columnWidths = headers.map(header => Math.max(header.length, ...rows.map(row => String(row[headers.indexOf(header)]).length)));
97
-
67
+
98
68
  let result = '';
99
-
69
+
100
70
  // 表头
101
71
  const headerRow = headers.map((header, i) => header.padEnd(columnWidths[i])).join(' │ ');
102
- result += `${this.colors.primary(headerRow)}\n`;
103
-
72
+ result += `${UIHelper.colors.primary(headerRow)}\n`;
73
+
104
74
  // 分隔线
105
75
  const separator = columnWidths.map(width => '─'.repeat(width)).join('─┼─');
106
- result += `${this.colors.muted(separator)}\n`;
107
-
76
+ result += `${UIHelper.colors.muted(separator)}\n`;
77
+
108
78
  // 数据行
109
79
  rows.forEach(row => {
110
80
  const dataRow = row.map((cell, i) => String(cell).padEnd(columnWidths[i])).join(' │ ');
111
- result += `${this.colors.info(dataRow)}\n`;
81
+ result += `${UIHelper.colors.info(dataRow)}\n`;
112
82
  });
113
-
83
+
114
84
  return result;
115
85
  }
116
86
 
87
+ // 剥离 ANSI 转义码后的可见字符长度
88
+ static _visibleLength(str) {
89
+ return str.replace(/\x1b\[[0-9;]*m/g, '').length;
90
+ }
91
+
117
92
  // 创建卡片式布局
118
93
  static createCard(title, content, icon = '') {
119
94
  const lines = content.split('\n');
120
- const maxLineLength = Math.max(...lines.map(line => line.length));
95
+ const maxLineLength = Math.max(...lines.map(line => UIHelper._visibleLength(line)));
96
+ const iconPrefix = icon ? `${icon} ` : '';
97
+ const titleVisible = UIHelper._visibleLength(title);
121
98
  const horizontalBorder = '─'.repeat(maxLineLength + 4);
122
-
123
- let result = `${this.colors.primary(`┌─${horizontalBorder}─┐`)}\n`;
124
- result += `${this.colors.primary('│')} ${chalk.bold.white(icon ? `${icon} ` : '')}${chalk.bold.white(title)}${' '.repeat(maxLineLength - title.length - (icon ? 2 : 0))} ${this.colors.primary('│')}\n`;
125
- result += `${this.colors.primary('├─')}${this.colors.muted(horizontalBorder)}${this.colors.primary('─┤')}\n`;
126
-
99
+
100
+ let result = `${UIHelper.colors.primary(`┌─${horizontalBorder}─┐`)}\n`;
101
+ result += `${UIHelper.colors.primary('│')} ${chalk.bold.white(iconPrefix)}${chalk.bold.white(title)}${' '.repeat(Math.max(0, maxLineLength - titleVisible - iconPrefix.length))} ${UIHelper.colors.primary('│')}\n`;
102
+ result += `${UIHelper.colors.primary('├─')}${UIHelper.colors.muted(horizontalBorder)}${UIHelper.colors.primary('─┤')}\n`;
103
+
127
104
  lines.forEach(line => {
128
- result += `${this.colors.primary('│')} ${this.colors.info(line)}${' '.repeat(maxLineLength - line.length)} ${this.colors.primary('│')}\n`;
105
+ result += `${UIHelper.colors.primary('│')} ${UIHelper.colors.info(line)}${' '.repeat(Math.max(0, maxLineLength - UIHelper._visibleLength(line)))} ${UIHelper.colors.primary('│')}\n`;
129
106
  });
130
-
131
- result += `${this.colors.primary('└─')}${this.colors.muted(horizontalBorder)}${this.colors.primary('─┘')}`;
107
+
108
+ result += `${UIHelper.colors.primary('└─')}${UIHelper.colors.muted(horizontalBorder)}${UIHelper.colors.primary('─┘')}`;
132
109
  return result;
133
110
  }
134
111
 
135
112
  // 创建操作菜单
136
113
  static createMenu(title, options) {
137
- let result = `${this.createTitle(title, this.icons.list)}\n\n`;
138
-
114
+ let result = `${UIHelper.createTitle(title, UIHelper.icons.list)}\n\n`;
115
+
139
116
  options.forEach((option, index) => {
140
- const number = this.colors.muted(`[${index + 1}]`);
117
+ const number = UIHelper.colors.muted(`[${index + 1}]`);
141
118
  const icon = option.icon || '•';
142
- const description = option.description ? this.colors.muted(` - ${option.description}`) : '';
143
- result += `${number} ${this.colors.accent(icon)} ${this.colors.info(option.label)}${description}\n`;
119
+ const description = option.description ? UIHelper.colors.muted(` - ${option.description}`) : '';
120
+ result += `${number} ${UIHelper.colors.accent(icon)} ${UIHelper.colors.info(option.label)}${description}\n`;
144
121
  });
145
-
146
- result += `\n${this.colors.muted(this.createSeparator())}\n`;
147
- result += `${this.colors.warning('请选择操作 (输入数字): ')}`;
148
-
122
+
123
+ result += `\n${UIHelper.colors.muted(UIHelper.createSeparator())}\n`;
124
+ result += `${UIHelper.colors.warning('请选择操作 (输入数字): ')}`;
125
+
149
126
  return result;
150
127
  }
151
128
 
152
129
  // 创建确认对话框
153
130
  static createConfirmDialog(message, options = ['确认', '取消']) {
154
- return `${this.colors.warning(message)}\n\n` +
155
- `${this.colors.success('[Y]')} ${this.colors.info(options[0])} ` +
156
- `${this.colors.error('[N]')} ${this.colors.info(options[1])}`;
131
+ return `${UIHelper.colors.warning(message)}\n\n` +
132
+ `${UIHelper.colors.success('[Y]')} ${UIHelper.colors.info(options[0])} ` +
133
+ `${UIHelper.colors.error('[N]')} ${UIHelper.colors.info(options[1])}`;
157
134
  }
158
135
 
159
136
  // 格式化时间
@@ -161,32 +138,32 @@ class UIHelper {
161
138
  const date = new Date(dateString);
162
139
  const now = new Date();
163
140
  const diff = now - date;
164
-
141
+
165
142
  if (diff < 60000) return '刚刚';
166
143
  if (diff < 3600000) return `${Math.floor(diff / 60000)} 分钟前`;
167
144
  if (diff < 86400000) return `${Math.floor(diff / 3600000)} 小时前`;
168
145
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)} 天前`;
169
-
146
+
170
147
  return date.toLocaleDateString('zh-CN');
171
148
  }
172
149
 
173
150
  // 创建搜索框
174
151
  static createSearchBox(placeholder = '搜索...') {
175
- return `${this.colors.info(this.icons.search)} ${this.colors.muted(placeholder)}`;
152
+ return `${UIHelper.colors.info(UIHelper.icons.search)} ${UIHelper.colors.muted(placeholder)}`;
176
153
  }
177
154
 
178
155
  // 创建提示框
179
156
  static createTooltip(text) {
180
- return `${this.colors.muted('💡 ' + text)}`;
157
+ return `${UIHelper.colors.muted('💡 ' + text)}`;
181
158
  }
182
159
 
183
160
  // 创建加载动画
184
161
  static createLoadingAnimation(text = '加载中...') {
185
162
  const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
186
163
  let frameIndex = 0;
187
-
164
+
188
165
  return setInterval(() => {
189
- process.stdout.write(`\r${this.colors.warning(frames[frameIndex])} ${this.colors.info(text)}`);
166
+ process.stdout.write(`\r${UIHelper.colors.warning(frames[frameIndex])} ${UIHelper.colors.info(text)}`);
190
167
  frameIndex = (frameIndex + 1) % frames.length;
191
168
  }, 100);
192
169
  }
@@ -199,12 +176,12 @@ class UIHelper {
199
176
 
200
177
  // 创建快捷键提示
201
178
  static createShortcutHint(key, action) {
202
- return `${this.colors.muted('[')}${this.colors.primary(key)}${this.colors.muted(']')} ${this.colors.info(action)}`;
179
+ return `${UIHelper.colors.muted('[')}${UIHelper.colors.primary(key)}${UIHelper.colors.muted(']')} ${UIHelper.colors.info(action)}`;
203
180
  }
204
181
 
205
182
  // 创建 ESC 键提示
206
183
  static createESCHint(action = '返回') {
207
- return `${this.colors.muted('[')}${this.colors.primary('ESC')}${this.colors.muted(']')} ${this.colors.info(action)}`;
184
+ return `${UIHelper.colors.muted('[')}${UIHelper.colors.primary('ESC')}${UIHelper.colors.muted(']')} ${UIHelper.colors.info(action)}`;
208
185
  }
209
186
 
210
187
  // 创建提示行
@@ -212,16 +189,49 @@ class UIHelper {
212
189
  if (!pairs.length) {
213
190
  return '';
214
191
  }
215
- const hints = pairs.map(([key, action]) => this.createShortcutHint(key, action));
216
- return `${this.colors.muted('提示: ')}${hints.join(this.colors.muted(' · '))}`;
192
+ const hints = pairs.map(([key, action]) => UIHelper.createShortcutHint(key, action));
193
+ return `${UIHelper.colors.muted('提示: ')}${hints.join(UIHelper.colors.muted(' · '))}`;
217
194
  }
218
195
 
219
196
  // 创建步骤指示
220
197
  static createStepIndicator(current, total, label) {
221
- const prefix = this.colors.muted(`步骤 ${current}/${total}`);
222
- const title = label ? ` ${this.colors.info(label)}` : '';
198
+ const prefix = UIHelper.colors.muted(`步骤 ${current}/${total}`);
199
+ const title = label ? ` ${UIHelper.colors.info(label)}` : '';
223
200
  return `${prefix}${title}`;
224
201
  }
225
202
  }
226
203
 
204
+ // 颜色主题
205
+ UIHelper.colors = {
206
+ primary: chalk.cyan,
207
+ secondary: chalk.blue,
208
+ success: chalk.green,
209
+ warning: chalk.yellow,
210
+ error: chalk.red,
211
+ info: chalk.white,
212
+ muted: chalk.gray,
213
+ accent: chalk.magenta
214
+ };
215
+
216
+ // 图标
217
+ UIHelper.icons = {
218
+ success: '✓',
219
+ error: '✗',
220
+ warning: '!',
221
+ info: 'i',
222
+ loading: '…',
223
+ arrow: '→',
224
+ back: '←',
225
+ home: '~',
226
+ settings: '*',
227
+ add: '+',
228
+ edit: '~',
229
+ delete: '-',
230
+ launch: '▶',
231
+ list: '≡',
232
+ config: '#',
233
+ current: '›',
234
+ search: '?'
235
+ };
236
+
227
237
  module.exports = { UIHelper };
@@ -1,7 +1,19 @@
1
+ /**
2
+ * Update Checker Utility
3
+ * 检查 npm 包更新
4
+ * @module utils/update-checker
5
+ */
6
+
1
7
  const chalk = require('chalk');
2
8
  const inquirer = require('inquirer');
3
9
  const spawn = require('cross-spawn');
4
10
 
11
+ /**
12
+ * 比较两个版本号
13
+ * @param {string} a - 版本号 A
14
+ * @param {string} b - 版本号 B
15
+ * @returns {number} -1 表示 a < b, 0 表示相等, 1 表示 a > b
16
+ */
5
17
  function compareVersions(a, b) {
6
18
  const pa = String(a).split('.').map(Number);
7
19
  const pb = String(b).split('.').map(Number);
@@ -15,21 +27,31 @@ function compareVersions(a, b) {
15
27
  return 0;
16
28
  }
17
29
 
30
+ /**
31
+ * 获取 npm 包的最新版本号
32
+ * @param {string} pkgName - 包名
33
+ * @param {number} [timeoutMs=4000] - 超时时间(毫秒)
34
+ * @returns {Promise<string|null>} 最新版本号,失败返回 null
35
+ */
18
36
  function getLatestVersion(pkgName, timeoutMs = 4000) {
19
- return new Promise((resolve, reject) => {
37
+ return new Promise((resolve, _reject) => {
20
38
  let done = false;
21
39
  const child = spawn('npm', ['view', pkgName, 'version', '--json'], {
22
- shell: process.platform === 'win32',
23
- stdio: ['ignore', 'pipe', 'ignore'],
40
+ shell: false,
41
+ stdio: ['ignore', 'pipe', 'ignore']
24
42
  });
25
43
 
26
44
  let out = '';
27
- child.stdout.on('data', (d) => (out += d.toString()))
45
+ child.stdout.on('data', (d) => (out += d.toString()));
28
46
 
29
47
  const t = setTimeout(() => {
30
48
  if (done) return;
31
49
  done = true;
32
- try { child.kill(); } catch {}
50
+ try {
51
+ child.kill();
52
+ } catch {
53
+ // npm view 超时后终止进程失败不影响更新检查结果。
54
+ }
33
55
  resolve(null);
34
56
  }, timeoutMs);
35
57
 
@@ -86,8 +108,8 @@ async function checkForUpdates({ packageName, currentVersion }) {
86
108
  type: 'confirm',
87
109
  name: 'doUpdate',
88
110
  message: '是否立即更新并重启?',
89
- default: false,
90
- },
111
+ default: false
112
+ }
91
113
  ]);
92
114
 
93
115
  if (!doUpdate) return;
@@ -95,8 +117,8 @@ async function checkForUpdates({ packageName, currentVersion }) {
95
117
  console.log(chalk.yellow('开始更新,请稍候...'));
96
118
  await new Promise((resolve) => {
97
119
  const child = spawn('npm', ['i', '-g', `${packageName}@latest`], {
98
- shell: process.platform === 'win32',
99
- stdio: 'inherit',
120
+ shell: false,
121
+ stdio: 'inherit'
100
122
  });
101
123
  child.on('close', (code) => resolve(code === 0));
102
124
  }).then((ok) => {
@@ -105,9 +127,15 @@ async function checkForUpdates({ packageName, currentVersion }) {
105
127
  return;
106
128
  }
107
129
  console.log(chalk.green('更新成功,正在重启...'));
108
- const child = spawn('cc', process.argv.slice(2), {
109
- shell: true,
110
- stdio: 'inherit',
130
+ const scriptPath = process.argv[1];
131
+ const restartCommand = scriptPath ? process.execPath : packageName;
132
+ const restartArgs = scriptPath
133
+ ? [scriptPath, ...process.argv.slice(2)]
134
+ : process.argv.slice(2);
135
+
136
+ const child = spawn(restartCommand, restartArgs, {
137
+ shell: false,
138
+ stdio: 'inherit'
111
139
  });
112
140
  child.on('close', (code) => {
113
141
  process.exit(code || 0);
@@ -115,6 +143,7 @@ async function checkForUpdates({ packageName, currentVersion }) {
115
143
  });
116
144
  }
117
145
  } catch {
146
+ // 更新检查必须静默失败,避免影响主命令执行。
118
147
  }
119
148
  }
120
149
 
@@ -1,17 +1,56 @@
1
+ const { getClaudeLaunchArgs } = require('./launch-args');
2
+ const { containsUnsafeTerminalCharacters } = require('./terminal-format');
3
+
1
4
  const validator = {
2
5
  validateName(name) {
3
6
  if (!name || typeof name !== 'string') {
4
7
  return '供应商名称不能为空';
5
8
  }
6
-
9
+
7
10
  if (name.trim().length === 0) {
8
11
  return '供应商名称不能为空或只包含空格';
9
12
  }
10
-
13
+
14
+ if (containsUnsafeTerminalCharacters(name)) {
15
+ return '供应商名称不能包含控制字符';
16
+ }
17
+
18
+ // 禁止使用保留名称 (Windows)
19
+ const reserved = [
20
+ '__PROTO__',
21
+ 'PROTOTYPE',
22
+ 'CONSTRUCTOR',
23
+ 'CON',
24
+ 'PRN',
25
+ 'AUX',
26
+ 'NUL',
27
+ 'COM1',
28
+ 'COM2',
29
+ 'COM3',
30
+ 'COM4',
31
+ 'COM5',
32
+ 'COM6',
33
+ 'COM7',
34
+ 'COM8',
35
+ 'COM9',
36
+ 'LPT1',
37
+ 'LPT2',
38
+ 'LPT3',
39
+ 'LPT4',
40
+ 'LPT5',
41
+ 'LPT6',
42
+ 'LPT7',
43
+ 'LPT8',
44
+ 'LPT9'
45
+ ];
46
+ if (reserved.includes(name.toUpperCase())) {
47
+ return '供应商名称不能使用系统保留名称';
48
+ }
49
+
11
50
  if (name.length > 100) {
12
51
  return '供应商名称不能超过100个字符';
13
52
  }
14
-
53
+
15
54
  return null;
16
55
  },
17
56
 
@@ -20,33 +59,58 @@ const validator = {
20
59
  if (displayName === null || displayName === undefined || displayName === '') {
21
60
  return null;
22
61
  }
23
-
62
+
24
63
  if (typeof displayName !== 'string') {
25
64
  return '显示名称必须是字符串';
26
65
  }
27
-
66
+
67
+ if (containsUnsafeTerminalCharacters(displayName)) {
68
+ return '显示名称不能包含控制字符';
69
+ }
70
+
28
71
  if (displayName.length > 100) {
29
72
  return '显示名称不能超过100个字符';
30
73
  }
31
-
74
+
32
75
  return null;
33
76
  },
34
77
 
35
78
  validateUrl(url, required = true) {
36
- if (!url || typeof url !== 'string') {
79
+ if (url === null || url === undefined || url === '') {
37
80
  return required ? 'URL不能为空' : null;
38
81
  }
39
-
82
+
83
+ if (typeof url !== 'string') {
84
+ return 'URL必须是字符串';
85
+ }
86
+
87
+ let parsedUrl;
40
88
  try {
41
- new URL(url);
42
- } catch (error) {
89
+ parsedUrl = new URL(url);
90
+ } catch {
43
91
  return '请输入有效的URL';
44
92
  }
45
-
46
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
93
+
94
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
47
95
  return 'URL必须以http://或https://开头';
48
96
  }
49
-
97
+
98
+ if (/[\x00-\x1F"\\]/.test(url)) {
99
+ return 'URL包含不安全字符';
100
+ }
101
+
102
+ const hostname = parsedUrl.hostname.toLowerCase();
103
+ const isLoopback =
104
+ hostname === 'localhost' ||
105
+ hostname.endsWith('.localhost') ||
106
+ hostname === '::1' ||
107
+ hostname === '[::1]' ||
108
+ /^127(?:\.\d{1,3}){3}$/.test(hostname);
109
+
110
+ if (parsedUrl.protocol === 'http:' && !isLoopback) {
111
+ return '远程 API 地址必须使用 HTTPS;HTTP 仅允许 localhost 或回环地址';
112
+ }
113
+
50
114
  return null;
51
115
  },
52
116
 
@@ -54,11 +118,40 @@ const validator = {
54
118
  if (!token || typeof token !== 'string') {
55
119
  return 'Token不能为空';
56
120
  }
57
-
58
- if (token.length < 10) {
59
- return 'Token长度不能少于10个字符';
121
+
122
+ if (token.trim().length === 0) {
123
+ return 'Token不能只包含空格';
124
+ }
125
+
126
+ if (containsUnsafeTerminalCharacters(token)) {
127
+ return 'Token不能包含控制字符';
128
+ }
129
+
130
+ // 检测常见的占位符文本
131
+ const placeholders = [
132
+ 'your-key-here',
133
+ 'your-token',
134
+ 'your_key',
135
+ 'your_token',
136
+ 'example',
137
+ 'test-key',
138
+ 'demo',
139
+ 'placeholder',
140
+ 'replace-me',
141
+ 'insert-key',
142
+ 'api-key-here',
143
+ 'token-here',
144
+ 'xxx',
145
+ 'yyy',
146
+ 'zzz',
147
+ 'abc123',
148
+ '123456'
149
+ ];
150
+ const lowerToken = token.toLowerCase();
151
+ if (placeholders.some(p => lowerToken.includes(p))) {
152
+ return 'Token 似乎是占位符,请输入真实的 API Token';
60
153
  }
61
-
154
+
62
155
  return null;
63
156
  },
64
157
 
@@ -67,91 +160,25 @@ const validator = {
67
160
  if (!model) {
68
161
  return null;
69
162
  }
70
-
163
+
71
164
  if (typeof model !== 'string') {
72
165
  return '模型名称必须是字符串';
73
166
  }
74
-
167
+
75
168
  if (model.trim().length === 0) {
76
169
  return '模型名称不能为空字符串';
77
170
  }
78
-
171
+
79
172
  if (model.length > 100) {
80
173
  return '模型名称不能超过100个字符';
81
174
  }
82
-
83
- return null;
84
- },
85
175
 
86
- validateLaunchArgs(args) {
87
- if (!Array.isArray(args)) {
88
- return '启动参数必须是数组';
89
- }
90
-
91
- const validArgs = [
92
- '--dangerously-skip-permissions',
93
- '--no-confirm',
94
- '--allow-all',
95
- '--auto-approve',
96
- '--yes',
97
- '--force'
98
- ];
99
-
100
- for (const arg of args) {
101
- if (!validArgs.includes(arg)) {
102
- return `无效的启动参数: ${arg}`;
103
- }
104
- }
105
-
106
176
  return null;
107
177
  },
108
178
 
109
179
  getAvailableLaunchArgs() {
110
- return [
111
- {
112
- name: '--continue',
113
- label: '继续上次对话',
114
- description: '恢复上次的对话记录',
115
- checked: false
116
- },
117
- {
118
- name: '--dangerously-skip-permissions',
119
- label: '最高权限',
120
- description: '仅限沙盒环境使用',
121
- checked: false
122
- },
123
- {
124
- name: '--no-confirm',
125
- label: '直接执行操作',
126
- description: '跳过确认提示',
127
- checked: false
128
- },
129
- {
130
- name: '--allow-all',
131
- label: '允许全部操作',
132
- description: '移除安全限制',
133
- checked: false
134
- },
135
- {
136
- name: '--auto-approve',
137
- label: '自动批准请求',
138
- description: '无需人工同意',
139
- checked: false
140
- },
141
- {
142
- name: '--yes',
143
- label: '默认回答 yes',
144
- description: '自动同意所有询问',
145
- checked: false
146
- },
147
- {
148
- name: '--force',
149
- label: '强制执行',
150
- description: '忽略可能的警告',
151
- checked: false
152
- }
153
- ];
180
+ return getClaudeLaunchArgs();
154
181
  }
155
182
  };
156
183
 
157
- module.exports = { validator };
184
+ module.exports = { validator };