codex-id 0.2.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.
@@ -0,0 +1,387 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { spawnSync } = require('node:child_process');
4
+ const { findCodexBin } = require('./codex');
5
+ const {
6
+ assertNotSymlink,
7
+ ensureDir,
8
+ ensureReadableFile,
9
+ getCodexHome,
10
+ writeFileAtomically,
11
+ } = require('./paths');
12
+ const {
13
+ currentAccount,
14
+ currentSlotLabel,
15
+ displayAccount,
16
+ readAccounts,
17
+ removeAccountEntry,
18
+ resolveAccount,
19
+ upsertAccount,
20
+ writeAccounts,
21
+ } = require('./accounts');
22
+ const { decodeAccountLabel, readAuth } = require('./auth');
23
+ const { refreshAuth, tokenExpiresSoon } = require('./refresh');
24
+ const usage = require('./usage');
25
+ const term = require('./terminal');
26
+
27
+ const TOTAL_RESET_TIME_THRESHOLD_SECONDS = 24 * 60 * 60;
28
+
29
+ // init 先做环境预检,失败时暴露真实缺失项而不是继续写账号库。
30
+ const runInitChecks = (env = process.env) => {
31
+ findCodexBin(env);
32
+ const codexHome = getCodexHome(env);
33
+ const authPath = path.join(codexHome, 'auth.json');
34
+ if (!fs.existsSync(codexHome)) throw new Error(`Codex 目录不存在:${codexHome}`);
35
+ assertNotSymlink(codexHome, '拒绝读取符号链接目录');
36
+ ensureReadableFile(authPath);
37
+ };
38
+
39
+ const syncCurrentAccount = (env = process.env, output = process.stdout) => {
40
+ const codexHome = getCodexHome(env);
41
+ const { account, overwritten } = upsertAccount(readAuth(codexHome), env);
42
+ if (overwritten) {
43
+ output.write(`账号已存在:${displayAccount(account)},已更新:${path.join(codexHome, 'codex-id.json')}\n`);
44
+ return;
45
+ }
46
+ output.write(`已同步当前 Codex 账号:${displayAccount(account)},已写入:${path.join(codexHome, 'codex-id.json')}\n`);
47
+ };
48
+
49
+ const initAccounts = (env = process.env, output = process.stdout) => {
50
+ runInitChecks(env);
51
+ output.write('环境检查通过,');
52
+ syncCurrentAccount(env, output);
53
+ };
54
+
55
+ // 清理登录中断遗留的临时目录,只处理 `.login.*` 且跳过符号链接。
56
+ const removeLoginTempDirs = (env = process.env) => {
57
+ const root = getCodexHome(env);
58
+ if (!fs.existsSync(root)) return;
59
+ for (const name of fs.readdirSync(root)) {
60
+ if (!name.startsWith('.login.')) continue;
61
+ const dir = path.join(root, name);
62
+ if (!fs.lstatSync(dir).isSymbolicLink()) fs.rmSync(dir, { recursive: true, force: true });
63
+ }
64
+ };
65
+
66
+ const useAccount = (selector, env = process.env, output = process.stdout) => {
67
+ const account = resolveAccount(selector, env);
68
+ if (!account) throw new Error(`账号不存在:${selector}`);
69
+ const codexHome = getCodexHome(env);
70
+ ensureDir(codexHome);
71
+ writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(account.auth, null, 2)}\n`);
72
+ output.write(`已切换 Codex 账号:${displayAccount(account)},已更新:${path.join(codexHome, 'auth.json')};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
73
+ };
74
+
75
+ const removeAccountFromStore = (account, message, env = process.env, output = process.stdout) => {
76
+ const accountLabel = displayAccount(account);
77
+ removeAccountEntry(account, env);
78
+ removeLoginTempDirs(env);
79
+ output.write(`${message}:${accountLabel}\n`);
80
+ };
81
+
82
+ const removeAccount = (selector, env = process.env, output = process.stdout) => {
83
+ const account = resolveAccount(selector, env);
84
+ if (!account) throw new Error(`账号不存在:${selector}`);
85
+ removeAccountFromStore(account, '已删除账号', env, output);
86
+ };
87
+
88
+ const writeEmptyAccountsMessage = (env = process.env, output = process.stdout) => {
89
+ output.write(`(${path.join(getCodexHome(env), 'codex-id.json')} 里还没有账号)\n`);
90
+ };
91
+
92
+ const formatCodexLoginFailure = (codexBin, result) => {
93
+ const details = [
94
+ 'codex login 执行失败',
95
+ `codex 路径:${codexBin}`,
96
+ `退出码:${result.status ?? '未知'}`,
97
+ ];
98
+ if (result.signal) details.push(`终止信号:${result.signal}`);
99
+ if (result.error) details.push(`错误信息:${result.error.message}`);
100
+ details.push(`请先单独运行确认 Codex CLI 可登录:${codexBin} login`);
101
+ return details.join('\n');
102
+ };
103
+
104
+ // 批量删除只处理探活确认离线的账号,每个账号仍逐个交互确认。
105
+ const removeOfflineAccounts = async (
106
+ env = process.env,
107
+ output = process.stdout,
108
+ input = process.stdin,
109
+ errOutput = process.stderr,
110
+ ) => {
111
+ ensureDir(getCodexHome(env));
112
+ removeLoginTempDirs(env);
113
+ const accounts = readAccounts(env);
114
+ if (accounts.length === 0) {
115
+ writeEmptyAccountsMessage(env, output);
116
+ return;
117
+ }
118
+
119
+ let removed = 0;
120
+ let abortedReason = '';
121
+ for (const [index, account] of accounts.entries()) {
122
+ const accountLabel = displayAccount(account);
123
+ const status = await term.withProgress(
124
+ `正在检测账号 ${index + 1}/${accounts.length}:${accountLabel}`,
125
+ () => usage.probeAccountStatus(account),
126
+ env,
127
+ );
128
+ if (status === 'unknown') {
129
+ errOutput.write(`无法确认账号在线状态,已跳过:${accountLabel}\n`);
130
+ continue;
131
+ }
132
+ if (status !== 'offline') continue;
133
+ let confirmed = false;
134
+ try {
135
+ confirmed = await term.confirmRemoval(accountLabel, input, output);
136
+ } catch (error) {
137
+ abortedReason = error && error.message ? error.message : String(error);
138
+ break;
139
+ }
140
+ if (!confirmed) continue;
141
+ removeAccountFromStore(account, '已删除离线账号', env, output);
142
+ removed += 1;
143
+ }
144
+ if (removed > 0) output.write(`本次共删除离线账号:${removed}\n`);
145
+ else if (!abortedReason) output.write('没有离线账号可删除\n');
146
+ if (abortedReason) {
147
+ // 已删账号摘要先写到 stdout,再抛错让 main 设非零退出码。
148
+ throw new Error(`${abortedReason}(已删除 ${removed} 个,剩余离线账号未处理)`);
149
+ }
150
+ };
151
+
152
+ // Windows 下 `.cmd/.bat` 不能直接 spawn,需要走 cmd.exe 包装。
153
+ const runCodexLogin = (codexBin, env) => {
154
+ const childEnv = { ...env, CODEX_HOME: env.CODEX_HOME };
155
+ if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(codexBin)) {
156
+ const comspec = env.ComSpec || env.COMSPEC || 'cmd.exe';
157
+ return spawnSync(
158
+ comspec,
159
+ ['/d', '/s', '/c', `"${codexBin}" login`],
160
+ { stdio: 'inherit', env: childEnv, windowsVerbatimArguments: true },
161
+ );
162
+ }
163
+ return spawnSync(codexBin, ['login'], { stdio: 'inherit', env: childEnv });
164
+ };
165
+
166
+ // 使用临时 CODEX_HOME 完成登录,成功后再移动到账号仓库。
167
+ const addAccount = async (env = process.env, output = process.stdout) => {
168
+ const codexBin = findCodexBin(env);
169
+ const root = getCodexHome(env);
170
+ ensureDir(root);
171
+ const tempHome = fs.mkdtempSync(path.join(root, '.login.'));
172
+ let keepTempHome = false;
173
+ try {
174
+ const result = runCodexLogin(codexBin, { ...env, CODEX_HOME: tempHome });
175
+ if (result.status !== 0) throw new Error(formatCodexLoginFailure(codexBin, result));
176
+ const auth = readAuth(tempHome);
177
+ const accountLabel = decodeAccountLabel(tempHome);
178
+ if (!accountLabel || !auth) {
179
+ keepTempHome = true;
180
+ throw new Error(`登录完成,但未能从 auth.json 解析出邮箱或短 ID\n临时目录保留在:${tempHome}`);
181
+ }
182
+ const { overwritten } = upsertAccount(auth, env);
183
+ fs.rmSync(tempHome, { recursive: true, force: true });
184
+ if (overwritten) {
185
+ output.write(`已覆盖已有账号:${accountLabel}\n`);
186
+ return;
187
+ }
188
+ output.write(`已添加账号:${accountLabel}\n`);
189
+ } catch (error) {
190
+ if (!keepTempHome) {
191
+ fs.rmSync(tempHome, { recursive: true, force: true });
192
+ }
193
+ throw error;
194
+ }
195
+ };
196
+
197
+ // 当前账号进入 limited/cooling/offline 后,才尝试切到第一个 available 账号。
198
+ const useDefaultAccount = async (env = process.env, output = process.stdout) => {
199
+ const accounts = readAccounts(env);
200
+ if (accounts.length === 0) {
201
+ writeEmptyAccountsMessage(env, output);
202
+ return;
203
+ }
204
+ const usageResults = await term.withProgress('正在查询账号额度...', () => usage.loadUsage(accounts), env);
205
+ if (!usage.hasUsageData(usageResults)) throw new Error('无法查询账号额度,未切换账号');
206
+ const activeAccount = currentAccount(env);
207
+ const currentKey = activeAccount ? activeAccount.id : '';
208
+ if (activeAccount && !usage.accountShouldAutoSwitch(usageResults, currentKey)) {
209
+ output.write(`当前 Codex 账号状态无需自动切换:${displayAccount(activeAccount)},未切换账号。\n`);
210
+ return;
211
+ }
212
+ const next = await term.withProgress(
213
+ activeAccount ? `正在检查当前账号额度:${displayAccount(activeAccount)}` : '正在选择 available 账号...',
214
+ () => findFirstAvailableAccount(accounts, usageResults, currentKey),
215
+ env,
216
+ );
217
+ if (!next) {
218
+ if (activeAccount) {
219
+ output.write(`当前 Codex 账号没有 available 替代账号:${displayAccount(activeAccount)},未切换账号。\n`);
220
+ return;
221
+ }
222
+ throw new Error('没有找到 available 账号,未切换账号');
223
+ }
224
+ useAccount(next.id, env, output);
225
+ };
226
+
227
+ const getUsageRowColor = ({ isOffline, planLabel, nextUsed, totalUsed, nextPercent, totalPercent }) => {
228
+ if (isOffline) return 'lightRed';
229
+ if (planLabel === 'Free') {
230
+ if (totalUsed >= 100 || totalPercent === '0%') return 'lightGray';
231
+ if (totalUsed >= 97) return 'lightYellow';
232
+ return '';
233
+ }
234
+ if (nextUsed >= 100 || nextPercent === '0%' || totalPercent === '0%') return 'lightGray';
235
+ if (nextUsed >= 97) return 'lightYellow';
236
+ return '';
237
+ };
238
+
239
+ const findFirstAvailableAccount = (accounts, usageResults, currentKey = '') => {
240
+ return accounts.find((account) => {
241
+ if (account.id === currentKey) return false;
242
+ return usage.accountIsAvailableForAutoSwitch(usageResults, account.id);
243
+ });
244
+ };
245
+
246
+ const lightStatusLabel = (account) => {
247
+ return account && account.auth ? '已登录' : '未登录';
248
+ };
249
+
250
+ // 组装列表行数据;已有 Usage 数据时不再额外探活。
251
+ const buildAccountRow = async (account, index, total, activeLabel, usageResults, env) => {
252
+ const accountLabel = displayAccount(account);
253
+ const key = account.id;
254
+ let status = lightStatusLabel(account);
255
+ let isOffline = false;
256
+ const isCurrent = Boolean(activeLabel && accountLabel === activeLabel);
257
+
258
+ if (status === '已登录' && !usage.usageAvailableForAccount(usageResults, key)) {
259
+ const probeStatus = await term.withProgress(`正在探活账号 ${index}/${total}:${accountLabel}`, () => usage.probeAccountStatus(account), env);
260
+ if (probeStatus === 'offline') {
261
+ status = '离线';
262
+ isOffline = true;
263
+ } else if (probeStatus === 'unknown') {
264
+ status = '未知';
265
+ }
266
+ }
267
+
268
+ return { account: accountLabel, isCurrent, isOffline, key, status, indexDisplay: term.formatListIndex(index, isCurrent) };
269
+ };
270
+
271
+ const loadAccountRows = async (accounts, activeLabel, usageResults, env = process.env) => {
272
+ return Promise.all(accounts.map((account, index) => {
273
+ return buildAccountRow(account, index + 1, accounts.length, activeLabel, usageResults, env);
274
+ }));
275
+ };
276
+
277
+ const getTotalResetMode = (resetAt) => {
278
+ const now = Math.floor(Date.now() / 1000);
279
+ return resetAt - now <= TOTAL_RESET_TIME_THRESHOLD_SECONDS ? 'time' : 'date';
280
+ };
281
+
282
+ const buildUsageColumns = (item) => {
283
+ const planLabel = term.formatPlanType(item.plan);
284
+ const nextReset = item.next_reset ?? item.h5_reset;
285
+ const totalReset = item.total_reset ?? item.d7_reset;
286
+ const nextPercent = term.formatUsagePercent(item.next_used ?? item.h5_used);
287
+ const totalPercent = term.formatUsagePercent(item.total_used ?? item.d7_used);
288
+ const nextColumn = nextPercent !== '-' && nextReset
289
+ ? `${nextPercent} (${term.formatResetTime(nextReset, 'time')})`
290
+ : nextPercent;
291
+ const totalColumn = totalPercent !== '-' && totalReset
292
+ ? `${totalPercent} (${term.formatResetTime(totalReset, getTotalResetMode(totalReset))})`
293
+ : totalPercent;
294
+
295
+ return { nextColumn, nextPercent, planLabel, totalColumn, totalPercent };
296
+ };
297
+
298
+ const renderUsageRow = (row, item, accountWidth, output = process.stdout) => {
299
+ const { nextColumn, nextPercent, planLabel, totalColumn, totalPercent } = buildUsageColumns(item);
300
+ const statusColor = getUsageRowColor({
301
+ isOffline: row.isOffline,
302
+ nextPercent,
303
+ nextUsed: item.next_used ?? item.h5_used,
304
+ planLabel,
305
+ totalPercent,
306
+ totalUsed: item.total_used ?? item.d7_used,
307
+ });
308
+ 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)}`;
309
+ term.printRow(line, { isCurrent: row.isCurrent, color: statusColor }, output);
310
+ };
311
+
312
+ const renderStatusRow = (row, accountWidth, output = process.stdout) => {
313
+ const line = `${term.pad(row.indexDisplay, term.INDEX_WIDTH)} ${term.pad(row.account, accountWidth)} ${term.pad(row.status, term.STATUS_WIDTH)}`;
314
+ term.printRow(line, { isCurrent: row.isCurrent, color: row.isOffline ? 'lightRed' : '' }, output);
315
+ };
316
+
317
+ const refreshAccountForList = async (account, activeLabel, env, services, errOutput) => {
318
+ if (!tokenExpiresSoon(account.auth)) return { account, refreshedCurrent: false, changed: false };
319
+ try {
320
+ const nextAuth = await refreshAuth(account.auth, env, services.refreshFetch);
321
+ if (!nextAuth) return { account, refreshedCurrent: false, changed: false };
322
+ const next = { ...account, auth: nextAuth };
323
+ return {
324
+ account: next,
325
+ changed: true,
326
+ refreshedCurrent: displayAccount(account) === activeLabel,
327
+ };
328
+ } catch (error) {
329
+ const message = error && error.message ? error.message : String(error);
330
+ errOutput.write(`续期失败:${displayAccount(account)}:${message}\n`);
331
+ return { account, refreshedCurrent: false, changed: false };
332
+ }
333
+ };
334
+
335
+ const refreshAccountsForList = async (accounts, activeLabel, env = process.env, services = {}) => {
336
+ const errOutput = services.errOutput || process.stderr;
337
+ const results = await Promise.all(accounts.map((account) => {
338
+ return refreshAccountForList(account, activeLabel, env, services, errOutput);
339
+ }));
340
+ if (!results.some((result) => result.changed)) return accounts;
341
+
342
+ const refreshed = results.map((result) => result.account);
343
+ writeAccounts(refreshed, env);
344
+ const current = results.find((result) => result.refreshedCurrent);
345
+ if (current) {
346
+ const codexHome = getCodexHome(env);
347
+ writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(current.account.auth, null, 2)}\n`);
348
+ }
349
+ return refreshed;
350
+ };
351
+
352
+ const listAccounts = async (env = process.env, output = process.stdout, services = {}) => {
353
+ ensureDir(getCodexHome(env));
354
+ const activeLabel = currentSlotLabel(env);
355
+ const accounts = await term.withProgress('正在刷新登录态...', () => {
356
+ return refreshAccountsForList(readAccounts(env), activeLabel, env, services);
357
+ }, env);
358
+ const usageResults = await term.withProgress('正在查询账号额度...', () => {
359
+ return usage.loadUsage(accounts, services.usageFetch);
360
+ }, env);
361
+ const hasUsage = usage.hasUsageData(usageResults);
362
+ const rows = await loadAccountRows(accounts, activeLabel, usageResults, env);
363
+ const accountWidth = Math.max('Account'.length, ...rows.map((r) => r.account.length));
364
+
365
+ const header = hasUsage
366
+ ? `${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)}`
367
+ : `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Status', term.STATUS_WIDTH)}`;
368
+ output.write(`${term.bold(header, env, output)}\n`);
369
+
370
+ for (const row of rows) {
371
+ const item = usage.usageFor(usageResults, row.key) || {};
372
+ if (hasUsage) renderUsageRow(row, item, accountWidth, output);
373
+ else renderStatusRow(row, accountWidth, output);
374
+ }
375
+ if (rows.length === 0) writeEmptyAccountsMessage(env, output);
376
+ };
377
+
378
+ module.exports = {
379
+ addAccount,
380
+ getUsageRowColor,
381
+ initAccounts,
382
+ listAccounts,
383
+ removeAccount,
384
+ removeOfflineAccounts,
385
+ useAccount,
386
+ useDefaultAccount,
387
+ };
package/src/paths.js ADDED
@@ -0,0 +1,96 @@
1
+ const fs = require('node:fs');
2
+ const os = require('node:os');
3
+ const path = require('node:path');
4
+
5
+ // Git Bash / MSYS 上 HOME 可能是 `/c/Users/x`,与 path.win32 不兼容;
6
+ // 转换成 `C:\Users\x` 让后续 path.join 在 Windows 上稳定工作。
7
+ const normalizeWindowsHome = (value) => {
8
+ if (!value) return value;
9
+ const msys = value.match(/^\/([a-zA-Z])(\/.*)?$/);
10
+ if (msys) return `${msys[1].toUpperCase()}:${(msys[2] || '').replace(/\//g, '\\')}`;
11
+ return value;
12
+ };
13
+
14
+ const getHomeDir = (env = process.env) => {
15
+ if (process.platform === 'win32') {
16
+ const profile = env.USERPROFILE
17
+ || (env.HOMEDRIVE && env.HOMEPATH ? `${env.HOMEDRIVE}${env.HOMEPATH}` : '')
18
+ || normalizeWindowsHome(env.HOME)
19
+ || os.homedir();
20
+ return profile;
21
+ }
22
+ return env.HOME || os.homedir();
23
+ };
24
+
25
+ const getCodexHome = (env = process.env) => {
26
+ return path.join(getHomeDir(env), '.codex');
27
+ };
28
+
29
+ const getAccountsFile = (env = process.env) => {
30
+ return path.join(getCodexHome(env), 'codex-id.json');
31
+ };
32
+
33
+ // 所有账号和 auth 文件操作前都拒绝符号链接,避免越界读写。
34
+ const assertNotSymlink = (targetPath, message) => {
35
+ if (!fs.existsSync(targetPath)) return;
36
+ if (fs.lstatSync(targetPath).isSymbolicLink()) {
37
+ throw new Error(`${message}:${targetPath}`);
38
+ }
39
+ };
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
+ const ensureDir = (dirPath) => {
50
+ fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });
51
+ assertNotSymlink(dirPath, '拒绝写入符号链接目录');
52
+ try { fs.chmodSync(dirPath, 0o700); } catch (_) {}
53
+ };
54
+
55
+ // 先写唯一临时文件再 rename,避免 auth.json 出现半写入状态或并发冲突。
56
+ const writeFileAtomically = (targetPath, data) => {
57
+ const targetDir = path.dirname(targetPath);
58
+ if (!fs.existsSync(targetDir)) {
59
+ throw new Error(`目标目录不存在:${targetDir}`);
60
+ }
61
+ assertNotSymlink(targetDir, '拒绝写入符号链接目录');
62
+ assertNotSymlink(targetPath, '拒绝覆盖符号链接文件');
63
+
64
+ const tempPath = path.join(
65
+ targetDir,
66
+ `.${path.basename(targetPath)}.tmp.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 10)}`,
67
+ );
68
+ let cleanupTemp = true;
69
+ try {
70
+ // wx:独占创建,避免命中已有文件或符号链接。
71
+ const fd = fs.openSync(tempPath, 'wx', 0o600);
72
+ try {
73
+ fs.writeSync(fd, data);
74
+ try { fs.fsyncSync(fd); } catch (_) {}
75
+ } finally {
76
+ fs.closeSync(fd);
77
+ }
78
+ try { fs.chmodSync(tempPath, 0o600); } catch (_) { /* Windows 忽略 */ }
79
+ fs.renameSync(tempPath, targetPath);
80
+ cleanupTemp = false;
81
+ } finally {
82
+ if (cleanupTemp) {
83
+ try { fs.unlinkSync(tempPath); } catch (_) {}
84
+ }
85
+ }
86
+ };
87
+
88
+ module.exports = {
89
+ assertNotSymlink,
90
+ ensureDir,
91
+ ensureReadableFile,
92
+ getAccountsFile,
93
+ getCodexHome,
94
+ getHomeDir,
95
+ writeFileAtomically,
96
+ };
package/src/refresh.js ADDED
@@ -0,0 +1,62 @@
1
+ const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
2
+ const DEFAULT_REFRESH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
3
+ const REFRESH_GRACE_SECONDS = 24 * 60 * 60;
4
+ const REQUEST_TIMEOUT_MS = 8000;
5
+
6
+ const decodeJwtPayload = (token) => {
7
+ if (typeof token !== 'string') return null;
8
+ const [, payload] = token.split('.');
9
+ if (!payload) return null;
10
+ 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'));
14
+ } catch (_) {
15
+ return null;
16
+ }
17
+ };
18
+
19
+ const tokenExpiresSoon = (auth, nowSeconds = Math.floor(Date.now() / 1000)) => {
20
+ const payload = decodeJwtPayload(auth && auth.tokens && auth.tokens.access_token);
21
+ if (!payload || typeof payload.exp !== 'number') return true;
22
+ return payload.exp - nowSeconds <= REFRESH_GRACE_SECONDS;
23
+ };
24
+
25
+ const buildRefreshBody = (refreshToken) => {
26
+ const body = new URLSearchParams();
27
+ body.set('client_id', CLIENT_ID);
28
+ body.set('grant_type', 'refresh_token');
29
+ body.set('refresh_token', refreshToken);
30
+ return body;
31
+ };
32
+
33
+ const refreshAuth = async (auth, env = process.env, fetchImpl = fetch) => {
34
+ const tokens = auth && auth.tokens;
35
+ if (!tokens || typeof tokens.refresh_token !== 'string') return null;
36
+ if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return null;
37
+
38
+ const response = await fetchImpl(env.CODEX_REFRESH_TOKEN_URL_OVERRIDE || DEFAULT_REFRESH_TOKEN_URL, {
39
+ method: 'POST',
40
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
41
+ body: buildRefreshBody(tokens.refresh_token),
42
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
43
+ });
44
+ if (!response.ok) throw new Error(`刷新接口返回 ${response.status}`);
45
+
46
+ const data = await response.json();
47
+ if (typeof data.access_token !== 'string') throw new Error('刷新响应缺少 access_token');
48
+ const nextTokens = {
49
+ ...tokens,
50
+ access_token: data.access_token,
51
+ refresh_token: typeof data.refresh_token === 'string' ? data.refresh_token : tokens.refresh_token,
52
+ };
53
+ if (typeof data.id_token === 'string') nextTokens.id_token = data.id_token;
54
+ if (typeof data.account_id === 'string') nextTokens.account_id = data.account_id;
55
+
56
+ return { ...auth, last_refresh: new Date().toISOString(), tokens: nextTokens };
57
+ };
58
+
59
+ module.exports = {
60
+ refreshAuth,
61
+ tokenExpiresSoon,
62
+ };
@@ -0,0 +1,156 @@
1
+ const readline = require('node:readline/promises');
2
+
3
+ const INDEX_WIDTH = 4;
4
+ const PLAN_WIDTH = 8;
5
+ const USAGE_WIDTH = 14;
6
+ const STATUS_WIDTH = 10;
7
+ const PROGRESS_INTERVAL_MS = 120;
8
+ const PROGRESS_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
9
+
10
+ const pad = (value, width) => {
11
+ return String(value).padEnd(width, ' ');
12
+ };
13
+
14
+ const colorize = (value, color, env = process.env, stream = process.stdout) => {
15
+ if (!stream.isTTY || env.NO_COLOR) return value;
16
+ const colors = {
17
+ green: 32,
18
+ lightGray: '38;2;230;230;230',
19
+ lightRed: '38;2;255;160;160',
20
+ lightYellow: '38;2;255;230;150',
21
+ };
22
+ return `\u001b[${colors[color]}m${value}\u001b[0m`;
23
+ };
24
+
25
+ const bold = (value, env = process.env, stream = process.stdout) => {
26
+ if (!stream.isTTY || env.NO_COLOR) return value;
27
+ return `\u001b[1m${value}\u001b[0m`;
28
+ };
29
+
30
+ const formatPlanType = (plan) => {
31
+ const names = {
32
+ free: 'Free',
33
+ plus: 'Plus',
34
+ prolite: 'ProLite',
35
+ pro: 'Pro',
36
+ team: 'Team',
37
+ business: 'Biz',
38
+ enterprise: 'Ent',
39
+ edu: 'Edu',
40
+ };
41
+ return names[plan] || plan || '-';
42
+ };
43
+
44
+ const formatUsagePercent = (used) => {
45
+ if (typeof used !== 'number' || used < 0 || used > 100) return '-';
46
+ return `${Math.round(100 - used)}%`;
47
+ };
48
+
49
+ const formatResetTime = (resetAt, mode = 'time') => {
50
+ if (typeof resetAt !== 'number') return '';
51
+ const now = Math.floor(Date.now() / 1000);
52
+ if (resetAt - now <= 0) return '已重置';
53
+ const date = new Date(resetAt * 1000);
54
+ if (mode === 'date') {
55
+ return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
56
+ }
57
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
58
+ };
59
+
60
+ const formatListIndex = (index, isCurrent) => {
61
+ return isCurrent ? `${index}*` : String(index);
62
+ };
63
+
64
+ // 删除离线账号必须由交互终端确认,避免脚本环境误删。
65
+ const confirmRemoval = async (
66
+ account,
67
+ input = process.stdin,
68
+ output = process.stdout,
69
+ ) => {
70
+ if (!input.isTTY) throw new Error('删除离线账号需要交互式终端确认');
71
+ output.write(`检测到离线账号:${account}\n`);
72
+ const rl = readline.createInterface({ input, output });
73
+ const answer = await rl.question('是否删除?1:确定 2:取消\n');
74
+ rl.close();
75
+ if (answer === '1') return true;
76
+ if (answer === '2') {
77
+ output.write(`已取消删除离线账号:${account}\n`);
78
+ } else {
79
+ output.write(`输入无效,已取消删除离线账号:${account}\n`);
80
+ }
81
+ return false;
82
+ };
83
+
84
+ const printRow = (
85
+ row,
86
+ { isCurrent = false, color = '' } = {},
87
+ output = process.stdout,
88
+ ) => {
89
+ if (isCurrent) {
90
+ const starIndex = row.indexOf('*');
91
+ if (starIndex !== -1) {
92
+ const before = row.slice(0, starIndex);
93
+ const after = row.slice(starIndex + 1);
94
+ const paint = (value) => (color ? colorize(value, color, process.env, output) : value);
95
+ output.write(`${paint(before)}${colorize('*', 'green', process.env, output)}${paint(after)}\n`);
96
+ return;
97
+ }
98
+ }
99
+ output.write(`${color ? colorize(row, color, process.env, output) : row}\n`);
100
+ };
101
+
102
+ const shouldShowProgress = (env = process.env, stream = process.stderr) => {
103
+ const value = env.CX_PROGRESS || 'auto';
104
+ if (['1', 'always', 'true'].includes(value)) return true;
105
+ if (['0', 'never', 'false'].includes(value)) return false;
106
+ return Boolean(stream.isTTY);
107
+ };
108
+
109
+ // 在 stderr 渲染可关闭的进度动画,stdout 保持给机器可读输出。
110
+ const startProgress = (message, env = process.env, stream = process.stderr) => {
111
+ if (!shouldShowProgress(env, stream)) return () => {};
112
+
113
+ let index = 0;
114
+ const writeFrame = () => {
115
+ stream.write(`\r\u001b[K${PROGRESS_FRAMES[index]} ${message}`);
116
+ index = (index + 1) % PROGRESS_FRAMES.length;
117
+ };
118
+ writeFrame();
119
+ const timer = setInterval(writeFrame, PROGRESS_INTERVAL_MS);
120
+
121
+ return () => {
122
+ clearInterval(timer);
123
+ stream.write('\r\u001b[K');
124
+ };
125
+ };
126
+
127
+ const withProgress = async (
128
+ message,
129
+ action,
130
+ env = process.env,
131
+ stream = process.stderr,
132
+ ) => {
133
+ const stop = startProgress(message, env, stream);
134
+ try {
135
+ return await action();
136
+ } finally {
137
+ stop();
138
+ }
139
+ };
140
+
141
+ module.exports = {
142
+ INDEX_WIDTH,
143
+ PLAN_WIDTH,
144
+ STATUS_WIDTH,
145
+ USAGE_WIDTH,
146
+ bold,
147
+ colorize,
148
+ confirmRemoval,
149
+ formatListIndex,
150
+ formatPlanType,
151
+ formatResetTime,
152
+ formatUsagePercent,
153
+ pad,
154
+ printRow,
155
+ withProgress,
156
+ };