@pikecode/api-key-manager 2.1.6 → 2.1.8

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/README.md CHANGED
@@ -120,6 +120,7 @@ Claude Code 支持两种认证模式:
120
120
  | Auth Token | `ANTHROPIC_AUTH_TOKEN` + `ANTHROPIC_BASE_URL` | 部分服务商 |
121
121
 
122
122
  Codex CLI 使用 `OPENAI_API_KEY` + `OPENAI_BASE_URL`。
123
+ 如果选择官方网页登录模式,AKM 会按供应商名称缓存 Codex 的官方 Session;同一个官方供应商会复用本地 Session,Session 失效时由 Codex CLI 重新触发浏览器授权。需要多个 OpenAI 官方账号时,为每个账号添加一个不同名称的 Codex 官方网页登录供应商即可。
123
124
 
124
125
  ### 切换供应商
125
126
 
@@ -145,6 +146,9 @@ akm my-provider -q
145
146
 
146
147
  # 以空参数启动
147
148
  akm my-provider --no-args
149
+
150
+ # Codex 官方网页登录模式下清理当前 Session 并重新网页登录
151
+ akm openai-work --relogin
148
152
  ```
149
153
 
150
154
  参数优先级:`--no-args` > `--quick`
@@ -334,6 +338,12 @@ API Key (OPENAI_API_KEY): sk-xxxxxxxx
334
338
  基础URL (OPENAI_BASE_URL): https://api.openai.com
335
339
  ```
336
340
 
341
+ 官方网页登录模式可以配置多个供应商名称,例如 `openai-work`、`openai-personal`。AKM 会把它们的 Session 分开缓存,切换时只恢复对应供应商的 Session。需要强制换号或重新授权时运行:
342
+
343
+ ```bash
344
+ akm openai-work --relogin
345
+ ```
346
+
337
347
  ### 多账号配置
338
348
 
339
349
  ```bash
package/bin/akm.js CHANGED
@@ -104,6 +104,7 @@ program
104
104
  .argument('[provider]', '直接切换到指定供应商')
105
105
  .option('-q, --quick', '快速启动(使用默认或上次的启动参数)')
106
106
  .option('--no-args', '以空参数启动(不使用任何启动参数)')
107
+ .option('--relogin', 'Codex 官方登录模式下清理当前 Session 并重新网页登录')
107
108
  .action(async (provider, options) => {
108
109
  try {
109
110
  await main(provider, options);
@@ -138,13 +139,15 @@ program
138
139
  .option('--claude', '仅显示 Claude Code 供应商')
139
140
  .option('-q, --quick', '快速启动(使用默认或上次的启动参数)')
140
141
  .option('--no-args', '以空参数启动(不使用任何启动参数)')
142
+ .option('--relogin', 'Codex 官方登录模式下清理当前 Session 并重新网页登录')
141
143
  .action(async (provider, options) => {
142
144
  try {
143
145
  const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
144
146
  await registry.executeCommand('switch', provider, {
145
147
  filter,
146
148
  quick: options.quick,
147
- noArgs: options.noArgs
149
+ noArgs: options.noArgs,
150
+ relogin: options.relogin
148
151
  });
149
152
  } catch (error) {
150
153
  console.error(chalk.red('❌ 切换失败:'), error.message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.1.6",
3
+ "version": "2.1.8",
4
4
  "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -40,17 +40,7 @@ async function promptProviderInfo(adder) {
40
40
  { name: UI_MESSAGES.AUTH_MODE_CODEX_CHATGPT_LOGIN, value: 'chatgpt_login' }
41
41
  ],
42
42
  default: 'api_key',
43
- when: async answers => {
44
- const isCodex = (answers.ideName || adder.presetIdeName) === 'codex';
45
- if (!isCodex) return false;
46
- try {
47
- await adder.configManager.ensureLoaded();
48
- const hasOfficialConfig = adder.configManager.getProvider('openai-official');
49
- return !hasOfficialConfig;
50
- } catch {
51
- return true;
52
- }
53
- }
43
+ when: answers => (answers.ideName || adder.presetIdeName) === 'codex'
54
44
  },
55
45
  {
56
46
  type: 'input',
@@ -60,15 +50,7 @@ async function promptProviderInfo(adder) {
60
50
  const err = validator.validateName(input);
61
51
  return err || true;
62
52
  },
63
- when: answers => {
64
- // 如果选择了官方登录,直接用 "openai-official",不需要输入名称
65
- if ((answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login') {
66
- return false;
67
- }
68
- return true;
69
- },
70
53
  default: answers => {
71
- // 官方登录模式下返回默认名称
72
54
  if ((answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login') {
73
55
  return 'openai-official';
74
56
  }
@@ -138,7 +120,7 @@ async function promptProviderInfo(adder) {
138
120
  {
139
121
  type: 'confirm',
140
122
  name: 'confirmCodexLogin',
141
- message: 'Codex 将使用官方 OpenAI 网页登录方式,启动时需要在浏览器中登录。确认继续?',
123
+ message: 'Codex 将使用官方 OpenAI 网页登录方式;首次启动或 Session 失效时需要浏览器登录。确认继续?',
142
124
  default: true,
143
125
  when: answers => (answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login'
144
126
  },
@@ -1,9 +1,9 @@
1
1
  const { executeWithEnv } = require('../../utils/env-launcher');
2
2
  const { executeCodexWithEnv } = require('../../utils/codex-launcher');
3
3
 
4
- async function launchProviderProcess(provider, selectedLaunchArgs) {
4
+ async function launchProviderProcess(provider, selectedLaunchArgs, options = {}) {
5
5
  if (provider.ideName === 'codex') {
6
- await executeCodexWithEnv(provider, selectedLaunchArgs);
6
+ await executeCodexWithEnv(provider, selectedLaunchArgs, options);
7
7
  return;
8
8
  }
9
9
 
@@ -34,6 +34,7 @@ class EnvSwitcher extends BaseCommand {
34
34
  this.activeStatusRefresh = null;
35
35
  this.filter = null;
36
36
  this.filteredProviders = null;
37
+ this.forceRelogin = false;
37
38
  this._refreshTimer = null;
38
39
  this.providerManager = new ProviderManager(this);
39
40
  }
@@ -188,7 +189,9 @@ class EnvSwitcher extends BaseCommand {
188
189
 
189
190
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}...`, UIHelper.icons.success));
190
191
  console.log();
191
- await launchProviderProcess(launchProvider, selectedLaunchArgs);
192
+ await launchProviderProcess(launchProvider, selectedLaunchArgs, {
193
+ forceRelogin: this.forceRelogin
194
+ });
192
195
 
193
196
  } catch (error) {
194
197
  UIHelper.clearLoadingAnimation(loadingInterval);
@@ -209,7 +212,9 @@ class EnvSwitcher extends BaseCommand {
209
212
 
210
213
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
211
214
  console.log();
212
- await launchProviderProcess(retryProvider, retryArgs);
215
+ await launchProviderProcess(retryProvider, retryArgs, {
216
+ forceRelogin: this.forceRelogin
217
+ });
213
218
  return;
214
219
  } catch (retryError) {
215
220
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
@@ -233,7 +238,9 @@ class EnvSwitcher extends BaseCommand {
233
238
 
234
239
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
235
240
  console.log();
236
- await launchProviderProcess(retryProvider, retryArgs);
241
+ await launchProviderProcess(retryProvider, retryArgs, {
242
+ forceRelogin: this.forceRelogin
243
+ });
237
244
  return;
238
245
  } catch (retryError) {
239
246
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
@@ -1017,6 +1024,7 @@ class EnvSwitcher extends BaseCommand {
1017
1024
  async function switchCommand(providerName, options = {}) {
1018
1025
  const switcher = new EnvSwitcher();
1019
1026
  switcher.filter = options.filter || null;
1027
+ switcher.forceRelogin = options.relogin === true;
1020
1028
 
1021
1029
  try {
1022
1030
  if (providerName) {
@@ -1,6 +1,7 @@
1
1
  const fs = require('fs-extra');
2
2
  const path = require('path');
3
3
  const os = require('os');
4
+ const crypto = require('crypto');
4
5
  const { validator } = require('./validator');
5
6
  const { writeFileAtomic } = require('./atomic-file');
6
7
 
@@ -8,6 +9,7 @@ const CODEX_DIR_NAME = '.codex';
8
9
  const CONFIG_TOML_FILE = 'config.toml';
9
10
  const AUTH_JSON_FILE = 'auth.json';
10
11
  const BACKUP_DIR_NAME = 'akm-backups';
12
+ const SESSION_CACHE_DIR_NAME = 'akm-session-cache';
11
13
  const BACKUP_LIMIT = 10;
12
14
  let backupSequence = 0;
13
15
 
@@ -321,6 +323,164 @@ async function shouldRemoveAuthJsonForChatGptLogin(authJsonPath) {
321
323
  return data.auth_mode === 'apikey' || Object.prototype.hasOwnProperty.call(data, 'OPENAI_API_KEY');
322
324
  }
323
325
 
326
+ function isChatGptLoginAuth(data) {
327
+ return Boolean(
328
+ data &&
329
+ typeof data === 'object' &&
330
+ !Array.isArray(data) &&
331
+ data.auth_mode &&
332
+ data.auth_mode !== 'apikey' &&
333
+ Object.prototype.hasOwnProperty.call(data, 'tokens')
334
+ );
335
+ }
336
+
337
+ function normalizeSessionKey(sessionKey) {
338
+ if (typeof sessionKey !== 'string' || sessionKey.trim().length === 0) {
339
+ return null;
340
+ }
341
+
342
+ return sessionKey.trim();
343
+ }
344
+
345
+ function buildSessionCacheAuthPath(codexHome, sessionKey = null) {
346
+ const normalizedKey = normalizeSessionKey(sessionKey);
347
+ if (!normalizedKey) {
348
+ return path.join(codexHome, SESSION_CACHE_DIR_NAME, AUTH_JSON_FILE);
349
+ }
350
+
351
+ const safePrefix = normalizedKey
352
+ .toLowerCase()
353
+ .replace(/[^a-z0-9._-]+/g, '-')
354
+ .replace(/^-+|-+$/g, '')
355
+ .slice(0, 48) || 'official';
356
+ const hash = crypto.createHash('sha256').update(normalizedKey).digest('hex').slice(0, 12);
357
+ return path.join(codexHome, SESSION_CACHE_DIR_NAME, `${safePrefix}-${hash}.auth.json`);
358
+ }
359
+
360
+ async function readJsonObjectIfExists(filePath) {
361
+ if (!(await fs.pathExists(filePath))) {
362
+ return null;
363
+ }
364
+
365
+ const data = await fs.readJson(filePath);
366
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
367
+ return null;
368
+ }
369
+
370
+ return data;
371
+ }
372
+
373
+ async function cacheChatGptLoginAuth(codexHome, authData, sessionKey = null) {
374
+ if (!isChatGptLoginAuth(authData)) {
375
+ return null;
376
+ }
377
+
378
+ const cacheAuthPath = buildSessionCacheAuthPath(codexHome, sessionKey);
379
+ const cacheDir = path.dirname(cacheAuthPath);
380
+ await fs.ensureDir(cacheDir);
381
+ await setSecureDirectoryPermissions(cacheDir);
382
+ await writeFileAtomic(cacheAuthPath, JSON.stringify(authData, null, 2), {
383
+ encoding: 'utf8',
384
+ mode: 0o600
385
+ });
386
+ await setSecurePermissions(cacheAuthPath);
387
+ return cacheAuthPath;
388
+ }
389
+
390
+ async function cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey = null) {
391
+ let authData;
392
+ try {
393
+ authData = await readJsonObjectIfExists(authJsonPath);
394
+ } catch {
395
+ return null;
396
+ }
397
+
398
+ return await cacheChatGptLoginAuth(codexHome, authData, sessionKey);
399
+ }
400
+
401
+ async function findCachedChatGptLoginAuth(codexHome, sessionKey = null) {
402
+ const candidatePaths = [];
403
+ if (normalizeSessionKey(sessionKey)) {
404
+ candidatePaths.push(buildSessionCacheAuthPath(codexHome, sessionKey));
405
+ } else {
406
+ candidatePaths.push(buildSessionCacheAuthPath(codexHome));
407
+ }
408
+
409
+ for (const cacheAuthPath of candidatePaths) {
410
+ try {
411
+ const data = await readJsonObjectIfExists(cacheAuthPath);
412
+ if (isChatGptLoginAuth(data)) {
413
+ return cacheAuthPath;
414
+ }
415
+ } catch {
416
+ // 忽略损坏缓存,继续尝试其他来源。
417
+ }
418
+ }
419
+
420
+ return null;
421
+ }
422
+
423
+ async function clearCachedChatGptLoginAuth(codexHome, sessionKey = null) {
424
+ const targetPaths = [buildSessionCacheAuthPath(codexHome, sessionKey)];
425
+ if (normalizeSessionKey(sessionKey)) {
426
+ targetPaths.push(buildSessionCacheAuthPath(codexHome));
427
+ }
428
+
429
+ await Promise.all([...new Set(targetPaths)].map(filePath => fs.remove(filePath)));
430
+ }
431
+
432
+ async function shouldRemoveAuthJsonForRelogin(authJsonPath) {
433
+ if (!(await fs.pathExists(authJsonPath))) {
434
+ return false;
435
+ }
436
+
437
+ try {
438
+ const data = await readJsonObjectIfExists(authJsonPath);
439
+ return isChatGptLoginAuth(data) || await shouldRemoveAuthJsonForChatGptLogin(authJsonPath);
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
444
+
445
+ async function findLatestChatGptLoginAuthBackup(codexHome) {
446
+ const backupRoot = path.join(codexHome, BACKUP_DIR_NAME);
447
+ if (!(await fs.pathExists(backupRoot))) {
448
+ return null;
449
+ }
450
+
451
+ const backupDirectories = (await fs.readdir(backupRoot))
452
+ .filter(name => name.startsWith('backup-'))
453
+ .sort()
454
+ .reverse();
455
+
456
+ for (const backupName of backupDirectories) {
457
+ const backupAuthPath = path.join(backupRoot, backupName, AUTH_JSON_FILE);
458
+ if (!(await fs.pathExists(backupAuthPath))) {
459
+ continue;
460
+ }
461
+
462
+ try {
463
+ const data = await fs.readJson(backupAuthPath);
464
+ if (isChatGptLoginAuth(data)) {
465
+ return backupAuthPath;
466
+ }
467
+ } catch {
468
+ // 跳过损坏的备份,继续寻找更早的可用登录态。
469
+ }
470
+ }
471
+
472
+ return null;
473
+ }
474
+
475
+ async function findChatGptLoginAuthSource(codexHome, sessionKey = null) {
476
+ const cachedAuth = await findCachedChatGptLoginAuth(codexHome, sessionKey);
477
+ if (cachedAuth || normalizeSessionKey(sessionKey)) {
478
+ return cachedAuth;
479
+ }
480
+
481
+ return await findLatestChatGptLoginAuthBackup(codexHome);
482
+ }
483
+
324
484
  async function readFileSnapshot(filePath) {
325
485
  if (!(await fs.pathExists(filePath))) {
326
486
  return { exists: false, content: null, mode: 0o600 };
@@ -384,7 +544,7 @@ async function applyCodexConfig(config, options = {}) {
384
544
  };
385
545
 
386
546
  // 所有旧文件必须在任何写入发生前完成校验和目标内容计算。
387
- await readExistingAuthJson(authJsonPath);
547
+ const existingAuthJson = await readExistingAuthJson(authJsonPath);
388
548
  const authJsonContent = buildAuthJson(config.authToken);
389
549
  let nextConfigToml = null;
390
550
  const existingToml = snapshots.configToml.exists
@@ -400,6 +560,9 @@ async function applyCodexConfig(config, options = {}) {
400
560
  }
401
561
  }
402
562
 
563
+ // API Key 模式会覆盖 auth.json,先持久缓存官方网页登录态,避免备份轮转后丢失。
564
+ await cacheChatGptLoginAuth(codexHome, existingAuthJson);
565
+
403
566
  // 修改用户 Codex 文件前保留最近备份,便于恢复登录态和自定义配置。
404
567
  await backupCodexFiles(codexHome);
405
568
 
@@ -438,13 +601,35 @@ async function clearCodexAkmConfig(options = {}) {
438
601
  try {
439
602
  const codexHome = await ensureCodexHome(options.codexHome);
440
603
  const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
604
+ const sessionKey = normalizeSessionKey(options.sessionKey);
605
+ const forceRelogin = options.forceRelogin === true;
606
+ const cachedAuthPath = forceRelogin ? null : await findChatGptLoginAuthSource(codexHome, sessionKey);
441
607
 
442
608
  // 备份当前配置
443
609
  await backupCodexFiles(codexHome);
610
+ if (forceRelogin) {
611
+ await clearCachedChatGptLoginAuth(codexHome, sessionKey);
612
+ } else if (!sessionKey) {
613
+ await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey);
614
+ }
444
615
 
445
616
  // 只移除 API Key 认证文件,避免破坏 Codex 官方网页登录态。
446
- if (await shouldRemoveAuthJsonForChatGptLogin(authJsonPath)) {
447
- await fs.remove(authJsonPath);
617
+ const shouldRemoveAuthJson = forceRelogin
618
+ ? await shouldRemoveAuthJsonForRelogin(authJsonPath)
619
+ : sessionKey
620
+ ? await shouldRemoveAuthJsonForRelogin(authJsonPath)
621
+ : await shouldRemoveAuthJsonForChatGptLogin(authJsonPath);
622
+ const shouldRestoreCachedAuth =
623
+ Boolean(cachedAuthPath) && (!(await fs.pathExists(authJsonPath)) || shouldRemoveAuthJson);
624
+
625
+ if (shouldRemoveAuthJson || shouldRestoreCachedAuth) {
626
+ if (shouldRestoreCachedAuth) {
627
+ await fs.copy(cachedAuthPath, authJsonPath);
628
+ await setSecurePermissions(authJsonPath);
629
+ await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey);
630
+ } else {
631
+ await fs.remove(authJsonPath);
632
+ }
448
633
  }
449
634
 
450
635
  // 清理 config.toml 中的 AKM 配置
@@ -464,12 +649,19 @@ async function clearCodexAkmConfig(options = {}) {
464
649
  }
465
650
  }
466
651
 
652
+ async function cacheCodexOfficialSession(options = {}) {
653
+ const codexHome = await ensureCodexHome(options.codexHome);
654
+ const { authJsonPath } = buildCodexPaths(codexHome);
655
+ return await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, options.sessionKey);
656
+ }
657
+
467
658
  module.exports = {
468
659
  resolveCodexHome,
469
660
  buildCodexPaths,
470
661
  readCodexFiles,
471
662
  applyCodexConfig,
472
663
  clearCodexAkmConfig,
664
+ cacheCodexOfficialSession,
473
665
  backupCodexFiles,
474
666
  removeTopLevelApiBaseUrl,
475
667
  removeAkmModelProvider,
@@ -1,6 +1,10 @@
1
1
  const spawn = require('cross-spawn');
2
2
  const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
- const { applyCodexConfig, clearCodexAkmConfig } = require('./codex-files');
3
+ const {
4
+ applyCodexConfig,
5
+ clearCodexAkmConfig,
6
+ cacheCodexOfficialSession
7
+ } = require('./codex-files');
4
8
  const { assertSupportedLaunchArgs } = require('./launch-args');
5
9
  const { validator } = require('./validator');
6
10
 
@@ -53,9 +57,11 @@ function buildCodexEnvVariables(config) {
53
57
  * 使用环境变量注入方式执行 Codex CLI
54
58
  * @param {object} config - 供应商配置
55
59
  * @param {string[]} launchArgs - 启动参数
60
+ * @param {object} options - 启动选项
61
+ * @param {boolean} options.forceRelogin - 是否强制清理官方登录态并重新网页登录
56
62
  * @returns {Promise<void>}
57
63
  */
58
- async function executeCodexWithEnv(config, launchArgs = []) {
64
+ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {}) {
59
65
  if (!config || config.ideName !== 'codex') {
60
66
  throw new Error('无效的 Codex 供应商配置');
61
67
  }
@@ -80,7 +86,10 @@ async function executeCodexWithEnv(config, launchArgs = []) {
80
86
  await applyCodexConfig(config);
81
87
  } else if (authMode === 'chatgpt_login') {
82
88
  // chatgpt_login 模式:清理 AKM 的配置,让 Codex 使用官方登录
83
- await clearCodexAkmConfig();
89
+ await clearCodexAkmConfig({
90
+ sessionKey: config.name,
91
+ forceRelogin: launchOptions.forceRelogin === true
92
+ });
84
93
  }
85
94
 
86
95
  // 处理参数:子命令放前面,选项放后面
@@ -113,8 +122,16 @@ async function executeCodexWithEnv(config, launchArgs = []) {
113
122
  process.stderr.write(data);
114
123
  });
115
124
 
116
- child.on('close', (code, signal) => {
125
+ child.on('close', async (code, signal) => {
117
126
  if (code === 0 || code === 130 || signal === 'SIGINT') {
127
+ try {
128
+ if (authMode === 'chatgpt_login') {
129
+ await cacheCodexOfficialSession({ sessionKey: config.name });
130
+ }
131
+ } catch (error) {
132
+ reject(new Error(`保存 Codex 官方登录 Session 失败: ${error.message}`));
133
+ return;
134
+ }
118
135
  resolve();
119
136
  } else {
120
137
  // 检查是否是"会话被锁定"或"已有活跃写入者"的错误