@pikecode/api-key-manager 2.0.1 → 2.0.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -77,6 +77,17 @@ async function promptProviderInfo(adder) {
77
77
  when: answers => (answers.ideName || adder.presetIdeName) !== 'codex'
78
78
  },
79
79
  // Codex‑specific prompts (manual entry)
80
+ {
81
+ type: 'list',
82
+ name: 'authMode',
83
+ message: UI_MESSAGES.SELECT_CODEX_AUTH_MODE,
84
+ choices: [
85
+ { name: UI_MESSAGES.AUTH_MODE_CODEX_API_KEY, value: 'api_key' },
86
+ { name: UI_MESSAGES.AUTH_MODE_CODEX_CHATGPT_LOGIN, value: 'chatgpt_login' }
87
+ ],
88
+ default: 'api_key',
89
+ when: answers => (answers.ideName || adder.presetIdeName) === 'codex'
90
+ },
80
91
  {
81
92
  type: 'input',
82
93
  name: 'baseUrl',
@@ -87,7 +98,7 @@ async function promptProviderInfo(adder) {
87
98
  const err = validator.validateUrl(input);
88
99
  return err || true;
89
100
  },
90
- when: answers => (answers.ideName || adder.presetIdeName) === 'codex'
101
+ when: answers => (answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode !== 'chatgpt_login'
91
102
  },
92
103
  {
93
104
  type: 'input',
@@ -98,7 +109,14 @@ async function promptProviderInfo(adder) {
98
109
  const err = validator.validateToken(input);
99
110
  return err || true;
100
111
  },
101
- when: answers => (answers.ideName || adder.presetIdeName) === 'codex'
112
+ when: answers => (answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode !== 'chatgpt_login'
113
+ },
114
+ {
115
+ type: 'confirm',
116
+ name: 'confirmCodexLogin',
117
+ message: 'Codex 将使用官方 OpenAI 网页登录方式,启动时需要在浏览器中登录。确认继续?',
118
+ default: true,
119
+ when: answers => (answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login'
102
120
  },
103
121
  {
104
122
  type: 'confirm',
@@ -55,6 +55,29 @@ async function saveProvider(adder, answers) {
55
55
  setAsDefault: answers.setAsDefault
56
56
  });
57
57
 
58
+ // 如果是首个 Codex 配置,自动创建官方登录配置
59
+ if (answers.ideName === 'codex') {
60
+ const existingCodexProviders = Object.values(adder.configManager.getAllProviders())
61
+ .filter(p => p.ideName === 'codex');
62
+
63
+ // 只有当刚才添加的是第一个 Codex 配置,且没有官方配置时才创建
64
+ if (existingCodexProviders.length === 1 && !adder.configManager.getProvider('openai-official')) {
65
+ await adder.configManager.addProvider('openai-official', {
66
+ displayName: 'OpenAI Official',
67
+ ideName: 'codex',
68
+ authMode: 'chatgpt_login',
69
+ baseUrl: null,
70
+ authToken: null,
71
+ codexFiles: null,
72
+ launchArgs: [],
73
+ primaryModel: null,
74
+ smallFastModel: null,
75
+ setAsDefault: false
76
+ });
77
+ Logger.info('✨ 自动创建官方登录配置: openai-official');
78
+ }
79
+ }
80
+
58
81
  // 打印摘要并返回主界面
59
82
  await printProviderSummary(adder, answers, launchArgs, modelConfig);
60
83
  await adder.pauseBeforeReturn();
@@ -66,7 +66,8 @@ class ProviderAdder extends BaseCommand {
66
66
  }
67
67
 
68
68
  if (answers.ideName === 'codex') {
69
- answers.authMode = 'openai_api_key';
69
+ // authMode 由用户在 prompts 中选择,不再强制覆盖
70
+ // 支持 api_key 和 chatgpt_login 两种模式
70
71
  answers.codexFiles = null;
71
72
 
72
73
  // Codex 启动参数配置
@@ -78,7 +78,7 @@ class ProviderRemover extends BaseCommand {
78
78
  }
79
79
  }
80
80
 
81
- async interactiveRemove() {
81
+ async interactiveRemove(options = {}) {
82
82
  await this.configManager.ensureLoaded();
83
83
  const providers = this.configManager.listProviders();
84
84
 
@@ -98,12 +98,14 @@ class ProviderRemover extends BaseCommand {
98
98
  checked: false
99
99
  }));
100
100
 
101
- // 设置 ESC 键监听
102
101
  const escListener = this.createESCListener(async () => {
103
102
  Logger.info('取消删除供应商');
104
- // 使用CommandRegistry避免循环引用
105
- const { registry } = require('../CommandRegistry');
106
- await registry.executeCommand('switch');
103
+ if (typeof options.onBack === 'function') {
104
+ await options.onBack();
105
+ } else {
106
+ const { registry } = require('../CommandRegistry');
107
+ await registry.executeCommand('switch');
108
+ }
107
109
  }, '取消删除');
108
110
 
109
111
  try {
@@ -49,8 +49,13 @@ class ProviderChoicesHelper {
49
49
  : chalk.magenta('[Claude]');
50
50
  const lastUsedLabel = isLastUsed ? UIHelper.colors.muted(' --- 上次使用') : '';
51
51
 
52
+ // 官方登录特殊标记
53
+ const authModeLabel = provider.authMode === 'chatgpt_login'
54
+ ? chalk.green(' 🌐 官方登录')
55
+ : '';
56
+
52
57
  return {
53
- name: `${icon} ${ideTag} ${UIHelper.formatProvider(provider)}${lastUsedLabel} ${statusLabel}`,
58
+ name: `${icon} ${ideTag} ${UIHelper.formatProvider(provider)}${authModeLabel}${lastUsedLabel} ${statusLabel}`,
54
59
  value: provider.name,
55
60
  short: provider.name
56
61
  };
@@ -214,7 +214,7 @@ class EnvSwitcher extends BaseCommand {
214
214
  }
215
215
 
216
216
  // 确定使用的启动参数
217
- let selectedArgs;
217
+ let selectedArgs = [];
218
218
  if (options.noArgs) {
219
219
  selectedArgs = [];
220
220
  Logger.info('使用空参数启动');
@@ -538,7 +538,7 @@ class EnvSwitcher extends BaseCommand {
538
538
  return await this.showQuickSettings();
539
539
  }
540
540
 
541
- return await this.showProviderDetails(result.provider);
541
+ return await this.showLaunchArgsSelection(result.provider);
542
542
  }
543
543
 
544
544
  async showStatistics() {
@@ -556,12 +556,16 @@ class EnvSwitcher extends BaseCommand {
556
556
  console.log(UIHelper.createTitle('使用统计', UIHelper.icons.info));
557
557
  console.log();
558
558
 
559
+ const earliestCreated = providers.length > 0
560
+ ? providers.reduce((min, p) => (p.createdAt && (!min.createdAt || p.createdAt < min.createdAt)) ? p : min, providers[0])
561
+ : null;
562
+
559
563
  const stats = [
560
564
  ['总供应商数', totalProviders],
561
565
  ['当前供应商', currentProvider ? currentProvider.displayName : '无'],
562
566
  ['总使用次数', totalUsage],
563
567
  ['最常用供应商', mostUsed ? mostUsed.displayName : '无'],
564
- ['创建时间', providers.length > 0 ? UIHelper.formatTime(providers[0].createdAt) : '无']
568
+ ['最早创建时间', earliestCreated?.createdAt ? UIHelper.formatTime(earliestCreated.createdAt) : '无']
565
569
  ];
566
570
 
567
571
  console.log(UIHelper.createTable(['项目', '数据'], stats));
@@ -923,7 +927,7 @@ class EnvSwitcher extends BaseCommand {
923
927
  const { ProviderRemover } = require('./remove');
924
928
  const remover = new ProviderRemover();
925
929
  try {
926
- await remover.remove();
930
+ await remover.interactiveRemove({ onBack: null });
927
931
  } finally {
928
932
  remover.destroy();
929
933
  }
package/src/config.js CHANGED
@@ -4,6 +4,7 @@ const os = require('os');
4
4
  const chalk = require('chalk');
5
5
  const { writeJsonAtomic } = require('./utils/atomic-file');
6
6
  const { validateAndNormalizeConfigData } = require('./utils/import-validator');
7
+ const { validator } = require('./utils/validator');
7
8
 
8
9
  /**
9
10
  * @typedef {Object} ProviderConfig
@@ -57,7 +58,7 @@ class ConfigManager {
57
58
  return null;
58
59
  }
59
60
  if (typeof value !== 'string') {
60
- return value;
61
+ return null;
61
62
  }
62
63
  const trimmed = value.trim();
63
64
  return trimmed.length === 0 ? null : trimmed;
@@ -134,6 +135,7 @@ class ConfigManager {
134
135
  await this._performSave(this.config, { skipConflictCheck: true });
135
136
  } else {
136
137
  this.config = validateAndNormalizeConfigData({ ...this.getDefaultConfig(), ...data });
138
+ this._warnAboutInsecureRemoteHttpProviders();
137
139
  }
138
140
 
139
141
  // 迁移旧的认证模式
@@ -193,6 +195,21 @@ class ConfigManager {
193
195
  }
194
196
  }
195
197
 
198
+ _warnAboutInsecureRemoteHttpProviders() {
199
+ for (const [name, provider] of Object.entries(this.config.providers || {})) {
200
+ if (!validator.isInsecureRemoteHttp(provider.baseUrl)) {
201
+ continue;
202
+ }
203
+
204
+ const providerName = provider.displayName || name;
205
+ console.log(
206
+ chalk.yellow(
207
+ `⚠️ 供应商 "${providerName}" 使用远程 HTTP,Token 将以明文传输: ${provider.baseUrl}`
208
+ )
209
+ );
210
+ }
211
+ }
212
+
196
213
  _migrateAuthModes() {
197
214
  // 迁移旧配置以保持向后兼容
198
215
  if (this.config.providers) {
@@ -89,6 +89,13 @@ const UI_MESSAGES = {
89
89
  // 认证模式
90
90
  AUTH_MODE_API_KEY: '🔑 ANTHROPIC_API_KEY - 大多数第三方代理使用',
91
91
  AUTH_MODE_AUTH_TOKEN: '🔐 ANTHROPIC_AUTH_TOKEN - 部分服务商使用',
92
+ AUTH_MODE_CODEX_API_KEY: '🔑 API Key - 使用 OpenAI API Key',
93
+ AUTH_MODE_CODEX_CHATGPT_LOGIN: '🌐 官方网页登录 - 使用 OpenAI 账号登录',
94
+
95
+ // Codex 特定提示
96
+ SELECT_CODEX_AUTH_MODE: '选择 Codex 认证方式:',
97
+ CODEX_CHATGPT_LOGIN_INFO: '使用官方 OpenAI 网页登录,Codex 启动时会打开浏览器',
98
+ CODEX_API_KEY_INFO: '使用 API Key 方式,支持官方或第三方代理',
92
99
 
93
100
  // 操作结果
94
101
  OPERATION_CANCELLED: '操作已取消',
@@ -404,11 +404,49 @@ async function applyCodexConfig(config, options = {}) {
404
404
  return { codexHome };
405
405
  }
406
406
 
407
+ /**
408
+ * 清理 AKM 的 Codex 配置,让 Codex 使用官方网页登录
409
+ * 删除 auth.json(这样 Codex 会提示登录)
410
+ * 清理 config.toml 中的 [model_providers.akm] 配置
411
+ * @param {object} options - 选项
412
+ * @returns {Promise<{codexHome: string}>}
413
+ */
414
+ async function clearCodexAkmConfig(options = {}) {
415
+ try {
416
+ const codexHome = await ensureCodexHome(options.codexHome);
417
+ const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
418
+
419
+ // 备份当前配置
420
+ await backupCodexFiles(codexHome);
421
+
422
+ // 如果 auth.json 存在就删除它(chatgpt_login 模式不需要)
423
+ if (await fs.pathExists(authJsonPath)) {
424
+ await fs.remove(authJsonPath);
425
+ }
426
+
427
+ // 清理 config.toml 中的 AKM 配置
428
+ if (await fs.pathExists(configTomlPath)) {
429
+ const existingToml = await fs.readFile(configTomlPath, 'utf8');
430
+ const cleanedToml = removeAkmModelProvider(removeTopLevelApiBaseUrl(existingToml));
431
+
432
+ if (cleanedToml !== existingToml) {
433
+ await writeFileAtomic(configTomlPath, cleanedToml, { encoding: 'utf8', mode: 0o600 });
434
+ await setSecurePermissions(configTomlPath);
435
+ }
436
+ }
437
+
438
+ return { codexHome };
439
+ } catch (error) {
440
+ throw new Error(`清理 Codex AKM 配置失败: ${error.message}`, { cause: error });
441
+ }
442
+ }
443
+
407
444
  module.exports = {
408
445
  resolveCodexHome,
409
446
  buildCodexPaths,
410
447
  readCodexFiles,
411
448
  applyCodexConfig,
449
+ clearCodexAkmConfig,
412
450
  backupCodexFiles,
413
451
  removeTopLevelApiBaseUrl,
414
452
  removeAkmModelProvider,
@@ -1,6 +1,6 @@
1
1
  const spawn = require('cross-spawn');
2
2
  const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
- const { applyCodexConfig } = require('./codex-files');
3
+ const { applyCodexConfig, clearCodexAkmConfig } = require('./codex-files');
4
4
  const { assertSupportedLaunchArgs } = require('./launch-args');
5
5
  const { validator } = require('./validator');
6
6
 
@@ -17,7 +17,15 @@ function buildCodexEnvVariables(config) {
17
17
  delete env.OPENAI_MODEL;
18
18
 
19
19
  try {
20
- // Codex CLI 使用 OpenAI 环境变量
20
+ // 确定认证模式,默认为 api_key(向后兼容)
21
+ const authMode = config.authMode || 'api_key';
22
+
23
+ // chatgpt_login 模式不设置环境变量,使用 Codex 官方登录
24
+ if (authMode === 'chatgpt_login') {
25
+ return env;
26
+ }
27
+
28
+ // api_key 模式使用 OpenAI 环境变量
21
29
  if (config.authToken) {
22
30
  env.OPENAI_API_KEY = sanitizeEnvValue(config.authToken);
23
31
  }
@@ -52,7 +60,11 @@ async function executeCodexWithEnv(config, launchArgs = []) {
52
60
  throw new Error('无效的 Codex 供应商配置');
53
61
  }
54
62
 
55
- if (!config.authToken) {
63
+ // 确定认证模式,默认为 api_key(向后兼容)
64
+ const authMode = config.authMode || 'api_key';
65
+
66
+ // api_key 模式需要 authToken,chatgpt_login 模式不需要
67
+ if (authMode === 'api_key' && !config.authToken) {
56
68
  throw new Error(`供应商 '${config.name}' 未配置 API Key,请使用 'akm edit ${config.name}' 添加`);
57
69
  }
58
70
 
@@ -61,10 +73,15 @@ async function executeCodexWithEnv(config, launchArgs = []) {
61
73
  // 在写入 Codex 配置文件前完成全部输入校验。
62
74
  const env = buildCodexEnvVariables(config);
63
75
 
64
- // 写入 ~/.codex/config.toml 和 ~/.codex/auth.json
65
- // 确保 Codex CLI 使用 API Key 认证方式
66
- // 这样用户也可以直接运行 `codex` 命令而无需通过 akm
67
- await applyCodexConfig(config);
76
+ // 根据认证模式处理配置文件
77
+ if (authMode === 'api_key') {
78
+ // 写入 ~/.codex/config.toml 和 ~/.codex/auth.json
79
+ // 确保 Codex CLI 使用 API Key 认证方式
80
+ await applyCodexConfig(config);
81
+ } else if (authMode === 'chatgpt_login') {
82
+ // chatgpt_login 模式:清理 AKM 的配置,让 Codex 使用官方登录
83
+ await clearCodexAkmConfig();
84
+ }
68
85
 
69
86
  // 处理参数:子命令放前面,选项放后面
70
87
  const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
@@ -74,7 +91,11 @@ async function executeCodexWithEnv(config, launchArgs = []) {
74
91
 
75
92
  clearTerminal();
76
93
 
77
- console.log('\n启动 Codex CLI...\n');
94
+ if (authMode === 'chatgpt_login') {
95
+ console.log('\n启动 Codex CLI (官方网页登录)...\n');
96
+ } else {
97
+ console.log('\n启动 Codex CLI...\n');
98
+ }
78
99
 
79
100
  return new Promise((resolve, reject) => {
80
101
  const child = spawn('codex', args, {
@@ -83,11 +104,11 @@ async function executeCodexWithEnv(config, launchArgs = []) {
83
104
  shell: false
84
105
  });
85
106
 
86
- child.on('close', (code) => {
87
- if (code === 0) {
107
+ child.on('close', (code, signal) => {
108
+ if (code === 0 || code === 130 || signal === 'SIGINT') {
88
109
  resolve();
89
110
  } else {
90
- reject(new Error(`Codex CLI 退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
111
+ reject(new Error(`Codex CLI 异常退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
91
112
  }
92
113
  });
93
114
 
@@ -27,11 +27,10 @@ function buildEnvVariables(config) {
27
27
  }
28
28
  env.ANTHROPIC_AUTH_TOKEN = sanitizeEnvValue(config.authToken);
29
29
  } else {
30
- // api_key 模式(默认)
31
- if (!config.baseUrl) {
32
- throw new Error('未配置基础地址');
30
+ // api_key 模式(默认):baseUrl 为空时使用官方 Anthropic API
31
+ if (config.baseUrl) {
32
+ env.ANTHROPIC_BASE_URL = sanitizeEnvValue(config.baseUrl);
33
33
  }
34
- env.ANTHROPIC_BASE_URL = sanitizeEnvValue(config.baseUrl);
35
34
  env.ANTHROPIC_API_KEY = sanitizeEnvValue(config.authToken);
36
35
  }
37
36
 
@@ -65,11 +64,11 @@ async function executeWithEnv(config, launchArgs = []) {
65
64
  shell: false
66
65
  });
67
66
 
68
- child.on('close', (code) => {
69
- if (code === 0) {
67
+ child.on('close', (code, signal) => {
68
+ if (code === 0 || code === 130 || signal === 'SIGINT') {
70
69
  resolve();
71
70
  } else {
72
- reject(new Error(`Claude Code 退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
71
+ reject(new Error(`Claude Code 异常退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
73
72
  }
74
73
  });
75
74
 
@@ -21,7 +21,7 @@ const providerSchema = {
21
21
  displayName: nullableString,
22
22
  alias: nullableString,
23
23
  ideName: { enum: ['claude', 'codex'] },
24
- authMode: { enum: ['api_key', 'api_token', 'auth_token', 'openai_api_key', null] },
24
+ authMode: { enum: ['api_key', 'api_token', 'auth_token', 'openai_api_key', 'chatgpt_login', null] },
25
25
  authToken: { type: ['string', 'null'], maxLength: 16384 },
26
26
  baseUrl: { type: ['string', 'null'], maxLength: 2048 },
27
27
  models: {
@@ -135,8 +135,10 @@ function validateAndNormalizeData(data, source) {
135
135
  const launchArgs = provider.launchArgs || [];
136
136
  const lastUsedArgs = provider.lastUsedArgs || [];
137
137
 
138
- // 本地配置、导入配置和交互式编辑必须共享同一套 URL 规则。
139
- const baseUrlError = validator.validateUrl(provider.baseUrl, false);
138
+ // 外部导入保持安全默认值;本地显式配置允许连接远程 HTTP 代理。
139
+ const baseUrlError = validator.validateUrl(provider.baseUrl, false, {
140
+ allowInsecureHttp: source !== 'import'
141
+ });
140
142
  if (baseUrlError) {
141
143
  throw new Error(`供应商 "${safeName}" 的基础 URL 无效: ${baseUrlError}`);
142
144
  }
@@ -313,7 +313,8 @@ class ProviderStatusChecker {
313
313
  }
314
314
 
315
315
  const baseUrl = provider.baseUrl || 'https://api.openai.com/v1';
316
- const modelsUrl = `${baseUrl.replace(/\/$/, '')}/models`;
316
+ const base = baseUrl.replace(/\/$/, '');
317
+ const modelsUrl = base.endsWith('/models') ? base : `${base}/models`;
317
318
 
318
319
  try {
319
320
  const controller = new AbortController();
@@ -1,6 +1,17 @@
1
1
  const { getClaudeLaunchArgs } = require('./launch-args');
2
2
  const { containsUnsafeTerminalCharacters } = require('./terminal-format');
3
3
 
4
+ function isLoopbackHostname(hostname) {
5
+ const normalizedHostname = hostname.toLowerCase();
6
+ return (
7
+ normalizedHostname === 'localhost' ||
8
+ normalizedHostname.endsWith('.localhost') ||
9
+ normalizedHostname === '::1' ||
10
+ normalizedHostname === '[::1]' ||
11
+ /^127(?:\.\d{1,3}){3}$/.test(normalizedHostname)
12
+ );
13
+ }
14
+
4
15
  const validator = {
5
16
  validateName(name) {
6
17
  if (!name || typeof name !== 'string') {
@@ -75,7 +86,7 @@ const validator = {
75
86
  return null;
76
87
  },
77
88
 
78
- validateUrl(url, required = true) {
89
+ validateUrl(url, required = true, options = {}) {
79
90
  if (url === null || url === undefined || url === '') {
80
91
  return required ? 'URL不能为空' : null;
81
92
  }
@@ -99,21 +110,30 @@ const validator = {
99
110
  return 'URL包含不安全字符';
100
111
  }
101
112
 
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) {
113
+ if (
114
+ parsedUrl.protocol === 'http:' &&
115
+ !isLoopbackHostname(parsedUrl.hostname) &&
116
+ options.allowInsecureHttp === false
117
+ ) {
111
118
  return '远程 API 地址必须使用 HTTPS;HTTP 仅允许 localhost 或回环地址';
112
119
  }
113
120
 
114
121
  return null;
115
122
  },
116
123
 
124
+ isInsecureRemoteHttp(url) {
125
+ if (typeof url !== 'string') {
126
+ return false;
127
+ }
128
+
129
+ try {
130
+ const parsedUrl = new URL(url);
131
+ return parsedUrl.protocol === 'http:' && !isLoopbackHostname(parsedUrl.hostname);
132
+ } catch {
133
+ return false;
134
+ }
135
+ },
136
+
117
137
  validateToken(token) {
118
138
  if (!token || typeof token !== 'string') {
119
139
  return 'Token不能为空';