codex-id 0.2.2 → 0.2.4

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/src/commands.js CHANGED
@@ -3,16 +3,16 @@ const path = require('node:path');
3
3
  const { spawnSync } = require('node:child_process');
4
4
  const { findCodexBin } = require('./codex');
5
5
  const {
6
- assertNotSymlink,
7
6
  ensureDir,
8
- ensureReadableFile,
7
+ getAccountsFile,
9
8
  getCodexHome,
10
9
  writeFileAtomically,
11
10
  } = require('./paths');
12
11
  const {
12
+ accountLabel,
13
13
  currentAccount,
14
- currentSlotLabel,
15
14
  displayAccount,
15
+ findLogin,
16
16
  normalizeAccount,
17
17
  readAccounts,
18
18
  removeAccountEntry,
@@ -28,30 +28,39 @@ const term = require('./terminal');
28
28
  const TOTAL_RESET_TIME_THRESHOLD_SECONDS = 24 * 60 * 60;
29
29
  const PERSONAL_TOKEN_PREFIX = /^Bearer\s+/i;
30
30
 
31
- // init 先做环境预检,失败时暴露真实缺失项而不是继续写账号库。
32
- const runInitChecks = (env = process.env) => {
33
- findCodexBin(env);
34
- const codexHome = getCodexHome(env);
35
- const authPath = path.join(codexHome, 'auth.json');
36
- if (!fs.existsSync(codexHome)) throw new Error(`Codex 目录不存在:${codexHome}`);
37
- assertNotSymlink(codexHome, '拒绝读取符号链接目录');
38
- ensureReadableFile(authPath);
31
+ const writeCurrentAuth = (auth, env = process.env) => {
32
+ const authPath = path.join(getCodexHome(env), 'auth.json');
33
+ writeFileAtomically(authPath, `${JSON.stringify(auth, null, 2)}\n`);
34
+ return authPath;
39
35
  };
40
36
 
41
- const syncCurrentAccount = (env = process.env, output = process.stdout) => {
42
- const codexHome = getCodexHome(env);
43
- const { account, overwritten } = upsertAccount(readAuth(codexHome), env);
44
- if (overwritten) {
45
- output.write(`账号已存在:${displayAccount(account)},已更新:${path.join(codexHome, 'codex-id.json')}\n`);
46
- return;
37
+ const refreshedAt = (auth) => Date.parse(auth.last_refresh) || 0;
38
+
39
+ // list / use 前把 Codex 当前登录态收进账号库,避免切走时丢掉它续期得到的新令牌。
40
+ // 登录态存在但读不懂时返回 false。
41
+ const syncCurrentAccount = (env = process.env, output = process.stdout, errOutput = process.stderr) => {
42
+ let current;
43
+ try {
44
+ const auth = readAuth(getCodexHome(env));
45
+ if (!auth) return true;
46
+ current = normalizeAccount(auth);
47
+ } catch (error) {
48
+ errOutput.write(`当前登录态未同步:${error.message}\n`);
49
+ return false;
47
50
  }
48
- output.write(`已同步当前 Codex 账号:${displayAccount(account)},已写入:${path.join(codexHome, 'codex-id.json')}\n`);
51
+ const stored = findLogin(readAccounts(env), current);
52
+ // 只用更新的登录态覆盖,避免冲掉刚用 add 写入账号库的新令牌。
53
+ if (stored && refreshedAt(current.auth) <= refreshedAt(stored.auth)) return true;
54
+ const { account } = upsertAccount(current.auth, env);
55
+ if (!stored) output.write(`已同步当前 Codex 账号:${accountLabel(account, readAccounts(env))}\n`);
56
+ return true;
49
57
  };
50
58
 
51
- const initAccounts = (env = process.env, output = process.stdout) => {
52
- runInitChecks(env);
53
- output.write('环境检查通过,');
54
- syncCurrentAccount(env, output);
59
+ // 切换会覆盖 auth.json,没能入库的登录态一旦覆盖就找不回来。
60
+ const syncBeforeSwitch = (env, output) => {
61
+ if (syncCurrentAccount(env, output)) return;
62
+ const authPath = path.join(getCodexHome(env), 'auth.json');
63
+ throw new Error(`为避免丢失当前登录态,未切换账号;请先备份或删除 ${authPath}`);
55
64
  };
56
65
 
57
66
  // 清理登录中断遗留的临时目录,只处理 `.login.*` 且跳过符号链接。
@@ -65,30 +74,38 @@ const removeLoginTempDirs = (env = process.env) => {
65
74
  }
66
75
  };
67
76
 
68
- const useAccount = (selector, env = process.env, output = process.stdout) => {
69
- const account = resolveAccount(selector, env);
70
- if (!account) throw new Error(`账号不存在:${selector}`);
71
- const codexHome = getCodexHome(env);
72
- ensureDir(codexHome);
73
- writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(account.auth, null, 2)}\n`);
74
- output.write(`已切换 Codex 账号:${displayAccount(account)},已更新:${path.join(codexHome, 'auth.json')};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
77
+ const activateAccount = (account, env = process.env, output = process.stdout) => {
78
+ ensureDir(getCodexHome(env));
79
+ const authPath = writeCurrentAuth(account.auth, env);
80
+ output.write(`已切换 Codex 账号:${accountLabel(account, readAccounts(env))},已更新:${authPath};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
75
81
  };
76
82
 
77
- const removeAccountFromStore = (account, message, env = process.env, output = process.stdout) => {
78
- const accountLabel = displayAccount(account);
79
- removeAccountEntry(account, env);
80
- removeLoginTempDirs(env);
81
- output.write(`${message}:${accountLabel}\n`);
83
+ const useAccount = (selector, env = process.env, output = process.stdout) => {
84
+ // 先按同步前的列表解析序号,与用户上次看到的编号一致。
85
+ const selected = resolveAccount(selector, env);
86
+ syncBeforeSwitch(env, output);
87
+ const account = selected
88
+ ? findLogin(readAccounts(env), selected)
89
+ : resolveAccount(selector, env);
90
+ if (!account) throw new Error(`账号不存在:${selector}`);
91
+ activateAccount(account, env, output);
82
92
  };
83
93
 
84
94
  const removeAccount = (selector, env = process.env, output = process.stdout) => {
85
95
  const account = resolveAccount(selector, env);
86
96
  if (!account) throw new Error(`账号不存在:${selector}`);
87
- removeAccountFromStore(account, '已删除账号', env, output);
97
+ const current = currentAccount(env);
98
+ const label = accountLabel(account, readAccounts(env));
99
+ if (current && current.key === account.key) {
100
+ throw new Error(`不能删除当前生效账号:${label},请先用 cid use 切换到其他账号`);
101
+ }
102
+ removeAccountEntry(account, env);
103
+ removeLoginTempDirs(env);
104
+ output.write(`已删除账号:${label}\n`);
88
105
  };
89
106
 
90
107
  const writeEmptyAccountsMessage = (env = process.env, output = process.stdout) => {
91
- output.write(`(${path.join(getCodexHome(env), 'codex-id.json')} 里还没有账号)\n`);
108
+ output.write(`(${getAccountsFile(env)} 里还没有账号)\n`);
92
109
  };
93
110
 
94
111
  const formatCodexLoginFailure = (codexBin, result) => {
@@ -103,54 +120,6 @@ const formatCodexLoginFailure = (codexBin, result) => {
103
120
  return details.join('\n');
104
121
  };
105
122
 
106
- // 批量删除只处理探活确认离线的账号,每个账号仍逐个交互确认。
107
- const removeOfflineAccounts = async (
108
- env = process.env,
109
- output = process.stdout,
110
- input = process.stdin,
111
- errOutput = process.stderr,
112
- ) => {
113
- ensureDir(getCodexHome(env));
114
- removeLoginTempDirs(env);
115
- const accounts = readAccounts(env);
116
- if (accounts.length === 0) {
117
- writeEmptyAccountsMessage(env, output);
118
- return;
119
- }
120
-
121
- let removed = 0;
122
- let abortedReason = '';
123
- for (const [index, account] of accounts.entries()) {
124
- const accountLabel = displayAccount(account);
125
- const status = await term.withProgress(
126
- `正在检测账号 ${index + 1}/${accounts.length}:${accountLabel}`,
127
- () => usage.probeAccountStatus(account),
128
- env,
129
- );
130
- if (status === 'unknown') {
131
- errOutput.write(`无法确认账号在线状态,已跳过:${accountLabel}\n`);
132
- continue;
133
- }
134
- if (status !== 'offline') continue;
135
- let confirmed = false;
136
- try {
137
- confirmed = await term.confirmRemoval(accountLabel, input, output);
138
- } catch (error) {
139
- abortedReason = error && error.message ? error.message : String(error);
140
- break;
141
- }
142
- if (!confirmed) continue;
143
- removeAccountFromStore(account, '已删除离线账号', env, output);
144
- removed += 1;
145
- }
146
- if (removed > 0) output.write(`本次共删除离线账号:${removed}\n`);
147
- else if (!abortedReason) output.write('没有离线账号可删除\n');
148
- if (abortedReason) {
149
- // 已删账号摘要先写到 stdout,再抛错让 main 设非零退出码。
150
- throw new Error(`${abortedReason}(已删除 ${removed} 个,剩余离线账号未处理)`);
151
- }
152
- };
153
-
154
123
  // Windows 下 `.cmd/.bat` 不能直接 spawn,需要走 cmd.exe 包装。
155
124
  const runCodexLogin = (codexBin, env) => {
156
125
  const childEnv = { ...env, CODEX_HOME: env.CODEX_HOME };
@@ -199,6 +168,12 @@ const addAccount = async (env = process.env, output = process.stdout) => {
199
168
  const normalizePersonalAccessToken = (token) => {
200
169
  const value = String(token || '').trim().replace(PERSONAL_TOKEN_PREFIX, '').trim();
201
170
  if (!value) throw new Error('缺少访问令牌');
171
+ // 必须在发请求前拦下:非法请求头的报错会带出完整令牌。
172
+ if (!/^[\x21-\x7e]+$/.test(value)) throw new Error('访问令牌含空白或非法字符');
173
+ if (value.startsWith('sk-')) {
174
+ throw new Error('cid add 不接受 API Key;请用 Codex 以 Key 登录后运行 cid list 同步');
175
+ }
176
+ if (!value.startsWith('at-')) throw new Error('访问令牌应以 at- 开头');
202
177
  return value;
203
178
  };
204
179
 
@@ -216,18 +191,28 @@ const addPersonalAccessToken = async (token, env = process.env, output = process
216
191
  };
217
192
 
218
193
  // 当前账号进入 limited/cooling/offline 后,才尝试切到第一个 available 账号。
194
+ // API Key 账号按量计费且没有额度数据:既不自动切走,也不会被自动选中。
219
195
  const useDefaultAccount = async (env = process.env, output = process.stdout) => {
196
+ syncBeforeSwitch(env, output);
220
197
  const accounts = readAccounts(env);
221
198
  if (accounts.length === 0) {
222
199
  writeEmptyAccountsMessage(env, output);
223
200
  return;
224
201
  }
202
+ const activeAccount = currentAccount(env);
203
+ if (activeAccount && activeAccount.isApiKey) {
204
+ output.write(`当前是 API Key 账号,不自动切换:${displayAccount(activeAccount)},未切换账号。\n`);
205
+ return;
206
+ }
225
207
  const usageResults = await term.withProgress('正在查询账号额度...', () => usage.loadUsage(accounts), env);
226
208
  if (!usage.hasUsageData(usageResults)) throw new Error('无法查询账号额度,未切换账号');
227
- const activeAccount = currentAccount(env);
228
- const currentKey = activeAccount ? activeAccount.id : '';
209
+ const currentKey = activeAccount ? activeAccount.key : '';
229
210
  if (activeAccount && !usage.accountShouldAutoSwitch(usageResults, currentKey)) {
230
- output.write(`当前 Codex 账号状态无需自动切换:${displayAccount(activeAccount)},未切换账号。\n`);
211
+ const item = usage.usageFor(usageResults, currentKey);
212
+ const reason = usage.getAccountUsageState(item) === usage.ACCOUNT_USAGE_STATES.UNKNOWN
213
+ ? `额度${describeFailure(item).text}`
214
+ : '状态无需自动切换';
215
+ output.write(`当前 Codex 账号${reason}:${displayAccount(activeAccount)},未切换账号。\n`);
231
216
  return;
232
217
  }
233
218
  const next = await term.withProgress(
@@ -242,12 +227,11 @@ const useDefaultAccount = async (env = process.env, output = process.stdout) =>
242
227
  }
243
228
  throw new Error('没有找到 available 账号,未切换账号');
244
229
  }
245
- useAccount(next.id, env, output);
230
+ activateAccount(next, env, output);
246
231
  };
247
232
 
248
- const getUsageRowColor = ({ isOffline, planLabel, nextUsed, totalUsed, nextPercent, totalPercent }) => {
249
- if (isOffline) return 'lightRed';
250
- if (planLabel === 'Free') {
233
+ const getUsageRowColor = ({ planLabel, nextUsed, totalUsed, nextPercent, totalPercent }) => {
234
+ if (planLabel === 'Free' || nextPercent === '-') {
251
235
  if (totalUsed >= 100 || totalPercent === '0%') return 'gray';
252
236
  if (totalUsed >= 97) return 'lightYellow';
253
237
  return '';
@@ -259,44 +243,11 @@ const getUsageRowColor = ({ isOffline, planLabel, nextUsed, totalUsed, nextPerce
259
243
 
260
244
  const findFirstAvailableAccount = (accounts, usageResults, currentKey = '') => {
261
245
  return accounts.find((account) => {
262
- if (account.id === currentKey) return false;
263
- return usage.accountIsAvailableForAutoSwitch(usageResults, account.id);
246
+ if (account.key === currentKey) return false;
247
+ return usage.accountIsAvailableForAutoSwitch(usageResults, account.key);
264
248
  });
265
249
  };
266
250
 
267
- const lightStatusLabel = (account) => {
268
- return account && account.auth ? '已登录' : '未登录';
269
- };
270
-
271
- // 组装列表行数据;已有 Usage 数据时不再额外探活。
272
- const buildAccountRow = async (account, index, total, activeLabel, usageResults, env) => {
273
- const localLabel = displayAccount(account);
274
- const item = usage.usageFor(usageResults, account.id) || {};
275
- const accountLabel = item.email || localLabel;
276
- const key = account.id;
277
- let status = lightStatusLabel(account);
278
- let isOffline = false;
279
- const isCurrent = Boolean(activeLabel && localLabel === activeLabel);
280
-
281
- if (status === '已登录' && !usage.usageAvailableForAccount(usageResults, key)) {
282
- const probeStatus = await term.withProgress(`正在探活账号 ${index}/${total}:${accountLabel}`, () => usage.probeAccountStatus(account), env);
283
- if (probeStatus === 'offline') {
284
- status = '离线';
285
- isOffline = true;
286
- } else if (probeStatus === 'unknown') {
287
- status = '未知';
288
- }
289
- }
290
-
291
- return { account: accountLabel, isCurrent, isOffline, key, status, indexDisplay: term.formatListIndex(index, isCurrent) };
292
- };
293
-
294
- const loadAccountRows = async (accounts, activeLabel, usageResults, env = process.env) => {
295
- return Promise.all(accounts.map((account, index) => {
296
- return buildAccountRow(account, index + 1, accounts.length, activeLabel, usageResults, env);
297
- }));
298
- };
299
-
300
251
  const getTotalResetMode = (resetAt) => {
301
252
  const now = Math.floor(Date.now() / 1000);
302
253
  return resetAt - now <= TOTAL_RESET_TIME_THRESHOLD_SECONDS ? 'time' : 'date';
@@ -304,49 +255,57 @@ const getTotalResetMode = (resetAt) => {
304
255
 
305
256
  const buildUsageColumns = (item) => {
306
257
  const planLabel = term.formatPlanType(item.plan);
307
- const nextReset = item.next_reset ?? item.h5_reset;
308
- const totalReset = item.total_reset ?? item.d7_reset;
309
- const nextPercent = term.formatUsagePercent(item.next_used ?? item.h5_used);
310
- const totalPercent = term.formatUsagePercent(item.total_used ?? item.d7_used);
311
- const nextColumn = nextPercent !== '-' && nextReset
312
- ? `${nextPercent} (${term.formatResetTime(nextReset, 'time')})`
258
+ const nextPercent = term.formatUsagePercent(item.next_used);
259
+ const totalPercent = term.formatUsagePercent(item.total_used);
260
+ const nextColumn = nextPercent !== '-' && item.next_reset
261
+ ? `${nextPercent} (${term.formatResetTime(item.next_reset, 'time')})`
313
262
  : nextPercent;
314
- const totalColumn = totalPercent !== '-' && totalReset
315
- ? `${totalPercent} (${term.formatResetTime(totalReset, getTotalResetMode(totalReset))})`
263
+ const totalColumn = totalPercent !== '-' && item.total_reset
264
+ ? `${totalPercent} (${term.formatResetTime(item.total_reset, getTotalResetMode(item.total_reset))})`
316
265
  : totalPercent;
317
266
 
318
267
  return { nextColumn, nextPercent, planLabel, totalColumn, totalPercent };
319
268
  };
320
269
 
321
- const renderUsageRow = (row, item, accountWidth, output = process.stdout) => {
270
+ // 没拿到额度时直接根据这次查询结果说明状态,不再重复请求。
271
+ const describeFailure = (item) => {
272
+ if (usage.getAccountUsageState(item) === usage.ACCOUNT_USAGE_STATES.OFFLINE) return { text: '离线', isOffline: true };
273
+ return { text: item.error ? `未知(${item.error})` : '未知(无额度数据)', isOffline: false };
274
+ };
275
+
276
+ const renderRow = (name, index, isCurrent, item, accountWidth, output = process.stdout) => {
277
+ const prefix = `${term.pad(term.formatListIndex(index, isCurrent), term.INDEX_WIDTH)} ${term.pad(name, accountWidth)}`;
278
+ if (item && item.isApiKey) {
279
+ term.printRow(`${prefix} API Key`, { isCurrent, color: '' }, output);
280
+ return;
281
+ }
282
+ if (!usage.hasUsageFields(item)) {
283
+ const { text, isOffline } = describeFailure(item);
284
+ term.printRow(`${prefix} ${text}`, { isCurrent, color: isOffline ? 'lightRed' : '' }, output);
285
+ return;
286
+ }
322
287
  const { nextColumn, nextPercent, planLabel, totalColumn, totalPercent } = buildUsageColumns(item);
323
- const statusColor = getUsageRowColor({
324
- isOffline: row.isOffline,
288
+ const color = getUsageRowColor({
325
289
  nextPercent,
326
- nextUsed: item.next_used ?? item.h5_used,
290
+ nextUsed: item.next_used,
327
291
  planLabel,
328
292
  totalPercent,
329
- totalUsed: item.total_used ?? item.d7_used,
293
+ totalUsed: item.total_used,
330
294
  });
331
- const line = `${term.pad(row.indexDisplay, term.INDEX_WIDTH)} ${term.pad(row.account, accountWidth)} ${term.pad(planLabel, term.PLAN_WIDTH)} ${term.pad(nextColumn, term.USAGE_WIDTH)} ${term.pad(totalColumn, term.USAGE_WIDTH)}`;
332
- term.printRow(line, { isCurrent: row.isCurrent, color: statusColor }, output);
295
+ const line = `${prefix} ${term.pad(planLabel, term.PLAN_WIDTH)} ${term.pad(nextColumn, term.USAGE_WIDTH)} ${term.pad(totalColumn, term.USAGE_WIDTH)}`;
296
+ term.printRow(line, { isCurrent, color }, output);
333
297
  };
334
298
 
335
- const renderStatusRow = (row, accountWidth, output = process.stdout) => {
336
- const line = `${term.pad(row.indexDisplay, term.INDEX_WIDTH)} ${term.pad(row.account, accountWidth)} ${term.pad(row.status, term.STATUS_WIDTH)}`;
337
- term.printRow(line, { isCurrent: row.isCurrent, color: row.isOffline ? 'lightRed' : '' }, output);
338
- };
339
-
340
- const refreshAccountForList = async (account, activeLabel, env, services, errOutput) => {
299
+ const refreshAccountForList = async (account, activeKey, env, services, errOutput) => {
341
300
  if (!tokenExpiresSoon(account.auth)) return { account, refreshedCurrent: false, changed: false };
342
301
  try {
343
- const nextAuth = await refreshAuth(account.auth, env, services.refreshFetch);
302
+ const nextAuth = await refreshAuth(account.auth, services.refreshFetch);
344
303
  if (!nextAuth) return { account, refreshedCurrent: false, changed: false };
345
304
  const next = { ...account, auth: nextAuth };
346
305
  return {
347
306
  account: next,
348
307
  changed: true,
349
- refreshedCurrent: displayAccount(account) === activeLabel,
308
+ refreshedCurrent: account.key === activeKey,
350
309
  };
351
310
  } catch (error) {
352
311
  const message = error && error.message ? error.message : String(error);
@@ -355,80 +314,71 @@ const refreshAccountForList = async (account, activeLabel, env, services, errOut
355
314
  }
356
315
  };
357
316
 
358
- const refreshAccountsForList = async (accounts, activeLabel, env = process.env, services = {}) => {
317
+ const refreshAccountsForList = async (accounts, activeKey, env = process.env, services = {}) => {
359
318
  const errOutput = services.errOutput || process.stderr;
360
319
  const results = await Promise.all(accounts.map((account) => {
361
- return refreshAccountForList(account, activeLabel, env, services, errOutput);
320
+ return refreshAccountForList(account, activeKey, env, services, errOutput);
362
321
  }));
363
322
  if (!results.some((result) => result.changed)) return accounts;
364
323
 
365
324
  const refreshed = results.map((result) => result.account);
366
325
  writeAccounts(refreshed, env);
367
326
  const current = results.find((result) => result.refreshedCurrent);
368
- if (current) {
369
- const codexHome = getCodexHome(env);
370
- writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(current.account.auth, null, 2)}\n`);
371
- }
327
+ if (current) writeCurrentAuth(current.account.auth, env);
372
328
  return refreshed;
373
329
  };
374
330
 
375
- const syncPersonalAccessTokenEmails = (accounts, usageResults, activeLabel, env = process.env) => {
331
+ const syncPersonalAccessTokenEmails = (accounts, usageResults, activeKey, env = process.env) => {
376
332
  let activeAuth = null;
377
333
  let changed = false;
378
334
  const synced = accounts.map((account) => {
379
- const item = usage.usageFor(usageResults, account.id);
335
+ const item = usage.usageFor(usageResults, account.key);
380
336
  if (!item || !item.email || account.email || !account.auth.personal_access_token) return account;
381
337
  const next = normalizeAccount({ ...account.auth, email: item.email });
382
- item.key = next.id;
383
338
  changed = true;
384
- if (displayAccount(account) === activeLabel) activeAuth = next.auth;
339
+ if (account.key === activeKey) activeAuth = next.auth;
385
340
  return next;
386
341
  });
387
342
  if (!changed) return accounts;
388
343
 
389
344
  writeAccounts(synced, env);
390
- if (activeAuth) {
391
- const codexHome = getCodexHome(env);
392
- writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(activeAuth, null, 2)}\n`);
393
- }
394
- return synced;
345
+ if (activeAuth) writeCurrentAuth(activeAuth, env);
346
+ // 账号库写入时会重新排序,按落盘顺序显示,保证编号与 use / remove 一致。
347
+ return readAccounts(env);
395
348
  };
396
349
 
397
350
  const listAccounts = async (env = process.env, output = process.stdout, services = {}) => {
398
351
  ensureDir(getCodexHome(env));
399
- const activeLabel = currentSlotLabel(env);
352
+ // 必须先同步再续期:Codex 可能已经轮换过 refresh_token。
353
+ syncCurrentAccount(env, output, services.errOutput || process.stderr);
354
+ const activeKey = currentAccount(env)?.key;
400
355
  const accounts = await term.withProgress('正在刷新登录态...', () => {
401
- return refreshAccountsForList(readAccounts(env), activeLabel, env, services);
356
+ return refreshAccountsForList(readAccounts(env), activeKey, env, services);
402
357
  }, env);
403
358
  const usageResults = await term.withProgress('正在查询账号额度...', () => {
404
359
  return usage.loadUsage(accounts, services.usageFetch);
405
360
  }, env);
406
- const syncedAccounts = syncPersonalAccessTokenEmails(accounts, usageResults, activeLabel, env);
407
- const hasUsage = usage.hasUsageData(usageResults);
408
- const rows = await loadAccountRows(syncedAccounts, activeLabel, usageResults, env);
409
- const accountWidth = Math.max('Account'.length, ...rows.map((r) => r.account.length));
410
-
411
- const header = hasUsage
412
- ? `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Plan', term.PLAN_WIDTH)} ${term.pad('Next', term.USAGE_WIDTH)} ${term.pad('Total', term.USAGE_WIDTH)}`
413
- : `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Status', term.STATUS_WIDTH)}`;
361
+ const syncedAccounts = syncPersonalAccessTokenEmails(accounts, usageResults, activeKey, env);
362
+ const names = syncedAccounts.map((account) => accountLabel(account, syncedAccounts));
363
+ const accountWidth = Math.max('Account'.length, ...names.map((name) => name.length));
364
+
365
+ const header = `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Plan', term.PLAN_WIDTH)} ${term.pad('Next', term.USAGE_WIDTH)} ${term.pad('Total', term.USAGE_WIDTH)}`;
414
366
  output.write(`${term.bold(header, env, output)}\n`);
415
367
 
416
- for (const row of rows) {
417
- const item = usage.usageFor(usageResults, row.key) || {};
418
- if (hasUsage) renderUsageRow(row, item, accountWidth, output);
419
- else renderStatusRow(row, accountWidth, output);
420
- }
421
- if (rows.length === 0) writeEmptyAccountsMessage(env, output);
368
+ const currentKey = currentAccount(env)?.key;
369
+ syncedAccounts.forEach((account, i) => {
370
+ const item = account.isApiKey ? account : usage.usageFor(usageResults, account.key);
371
+ renderRow(names[i], i + 1, account.key === currentKey, item, accountWidth, output);
372
+ });
373
+ if (syncedAccounts.length === 0) writeEmptyAccountsMessage(env, output);
422
374
  };
423
375
 
424
376
  module.exports = {
425
377
  addAccount,
426
378
  addPersonalAccessToken,
427
379
  getUsageRowColor,
428
- initAccounts,
429
380
  listAccounts,
430
381
  removeAccount,
431
- removeOfflineAccounts,
432
382
  useAccount,
433
383
  useDefaultAccount,
434
384
  };
package/src/paths.js CHANGED
@@ -38,20 +38,22 @@ const assertNotSymlink = (targetPath, message) => {
38
38
  }
39
39
  };
40
40
 
41
- const ensureReadableFile = (filePath) => {
42
- if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
43
- throw new Error(`文件不存在:${filePath}`);
44
- }
45
- assertNotSymlink(filePath, '拒绝读取符号链接文件');
46
- fs.accessSync(filePath, fs.constants.R_OK);
47
- };
48
-
49
41
  const ensureDir = (dirPath) => {
50
42
  fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });
51
43
  assertNotSymlink(dirPath, '拒绝写入符号链接目录');
52
44
  try { fs.chmodSync(dirPath, 0o700); } catch (_) {}
53
45
  };
54
46
 
47
+ // 不透传解析错误:其中带文件原文,可能含令牌。
48
+ const readJsonFile = (filePath) => {
49
+ const text = fs.readFileSync(filePath, 'utf8');
50
+ try {
51
+ return JSON.parse(text);
52
+ } catch (_) {
53
+ throw new Error(`${filePath} 不是有效的 JSON`);
54
+ }
55
+ };
56
+
55
57
  // 先写唯一临时文件再 rename,避免 auth.json 出现半写入状态或并发冲突。
56
58
  const writeFileAtomically = (targetPath, data) => {
57
59
  const targetDir = path.dirname(targetPath);
@@ -88,9 +90,9 @@ const writeFileAtomically = (targetPath, data) => {
88
90
  module.exports = {
89
91
  assertNotSymlink,
90
92
  ensureDir,
91
- ensureReadableFile,
92
93
  getAccountsFile,
93
94
  getCodexHome,
94
95
  getHomeDir,
96
+ readJsonFile,
95
97
  writeFileAtomically,
96
98
  };
package/src/proxy.js ADDED
@@ -0,0 +1,66 @@
1
+ const { execFileSync } = require('node:child_process');
2
+ const http = require('node:http');
3
+ const path = require('node:path');
4
+
5
+ // cid 只访问 HTTPS 地址,系统代理只需取 HTTPS 一项。
6
+ const parseScutil = (text) => {
7
+ const read = (key) => (text.match(new RegExp(`^ ${key} : (.*)$`, 'm')) || [])[1];
8
+ const server = read('HTTPSEnable') === '1' && read('HTTPSProxy') ? `${read('HTTPSProxy')}:${read('HTTPSPort')}` : '';
9
+ return { server, unsupported: read('SOCKSEnable') === '1' || read('ProxyAutoConfigEnable') === '1' };
10
+ };
11
+
12
+ // ProxyServer 可能是 `host:port` 或 `http=..;https=..;socks=..`。
13
+ const parseRegistry = (text) => {
14
+ const read = (key) => (text.match(new RegExp(`^\\s+${key}\\s+REG_\\w+\\s+(\\S+)`, 'm')) || [])[1] || '';
15
+ const value = read('ProxyEnable') === '0x1' ? read('ProxyServer') : '';
16
+ const server = value.includes('=') ? (value.match(/(?:^|;)https=([^;]+)/) || [])[1] || '' : value;
17
+ return { server, unsupported: Boolean(read('AutoConfigURL')) || value.includes('socks=') };
18
+ };
19
+
20
+ // 环境变量优先;否则 macOS / Windows 读系统代理,Linux / WSL 只认环境变量。
21
+ const resolveProxy = (env = process.env, platform = process.platform, run = execFileSync) => {
22
+ const fromEnv = env.https_proxy || env.HTTPS_PROXY;
23
+ // Node 遇到 SOCKS 地址会静默直连,必须自己提示。
24
+ if (/^socks/i.test(fromEnv || '')) return { warning: '代理环境变量是 SOCKS,暂不支持' };
25
+ if (fromEnv) return { proxyEnv: env };
26
+ const options = { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] };
27
+ let system = { server: '' };
28
+ try {
29
+ if (platform === 'darwin') {
30
+ system = parseScutil(run('/usr/sbin/scutil', ['--proxy'], options));
31
+ } else if (platform === 'win32') {
32
+ // 用绝对路径,避免执行到当前目录里的同名程序。
33
+ const reg = path.win32.join(env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe');
34
+ const key = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
35
+ system = parseRegistry(run(reg, ['query', key], options));
36
+ }
37
+ } catch (_) {
38
+ return { warning: '读取系统代理失败' };
39
+ }
40
+ const { server, unsupported } = system;
41
+ if (server) return { proxyEnv: { HTTPS_PROXY: server.includes('://') ? server : `http://${server}` } };
42
+ return unsupported ? { warning: '系统代理是 PAC 或 SOCKS,暂不支持' } : {};
43
+ };
44
+
45
+ // Node 的 fetch 默认不读代理配置,需显式启用。
46
+ const setupProxy = (env = process.env, errOutput = process.stderr) => {
47
+ const warn = (reason) => errOutput.write(`警告:${reason},本次未启用代理(见 README「代理」)\n`);
48
+ const { proxyEnv, warning } = resolveProxy(env);
49
+ if (warning) warn(warning);
50
+ if (!proxyEnv) return;
51
+ if (!http.setGlobalProxyFromEnv) {
52
+ errOutput.write('警告:自动启用代理需要 Node 24.14+ 或 25.4+\n');
53
+ return;
54
+ }
55
+ try {
56
+ http.setGlobalProxyFromEnv(proxyEnv);
57
+ } catch (_) {
58
+ // 不回显代理地址,其中可能带账号密码。
59
+ warn('代理地址无效(需以 http:// 或 https:// 开头)');
60
+ }
61
+ };
62
+
63
+ module.exports = {
64
+ resolveProxy,
65
+ setupProxy,
66
+ };
package/src/refresh.js CHANGED
@@ -1,5 +1,7 @@
1
+ const { decodeBase64Url } = require('./auth');
2
+
1
3
  const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
2
- const DEFAULT_REFRESH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
4
+ const REFRESH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
3
5
  const REFRESH_GRACE_SECONDS = 24 * 60 * 60;
4
6
  const REQUEST_TIMEOUT_MS = 8000;
5
7
 
@@ -8,9 +10,7 @@ const decodeJwtPayload = (token) => {
8
10
  const [, payload] = token.split('.');
9
11
  if (!payload) return null;
10
12
  try {
11
- const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');
12
- const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
13
- return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
13
+ return JSON.parse(decodeBase64Url(payload));
14
14
  } catch (_) {
15
15
  return null;
16
16
  }
@@ -30,12 +30,11 @@ const buildRefreshBody = (refreshToken) => {
30
30
  return body;
31
31
  };
32
32
 
33
- const refreshAuth = async (auth, env = process.env, fetchImpl = fetch) => {
33
+ const refreshAuth = async (auth, fetchImpl = fetch) => {
34
34
  const tokens = auth && auth.tokens;
35
35
  if (!tokens || typeof tokens.refresh_token !== 'string') return null;
36
- if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return null;
37
36
 
38
- const response = await fetchImpl(env.CODEX_REFRESH_TOKEN_URL_OVERRIDE || DEFAULT_REFRESH_TOKEN_URL, {
37
+ const response = await fetchImpl(REFRESH_TOKEN_URL, {
39
38
  method: 'POST',
40
39
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
41
40
  body: buildRefreshBody(tokens.refresh_token),