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.
package/README.md ADDED
@@ -0,0 +1,226 @@
1
+ # codex-id
2
+
3
+ `codex-id` 是一个轻量的 Codex 账号切换 CLI,命令名为 `cid`。
4
+
5
+ 它把账号统一存放在 `~/.codex/codex-id.json`,切换时再把选中账号的
6
+ `auth` 写入当前生效槽位 `~/.codex/auth.json`:
7
+
8
+ ```text
9
+ ~/.codex/
10
+ ├── auth.json # 当前生效账号
11
+ └── codex-id.json # codex-id 账号库
12
+ ```
13
+
14
+ `codex-id.json` 只保存最小结构:
15
+
16
+ ```json
17
+ {
18
+ "version": 1,
19
+ "accounts": [
20
+ {
21
+ "tokens": {
22
+ "id_token": "...",
23
+ "access_token": "...",
24
+ "account_id": "..."
25
+ }
26
+ }
27
+ ]
28
+ }
29
+ ```
30
+
31
+ CLI 不会打印 token。它优先从 `auth.json` 的 `id_token` payload 中解析
32
+ `email`;如果没有邮箱,再回退到 `tokens.account_id` 的前 8 位,
33
+ 用于列表显示和账号选择。
34
+
35
+ ## 运行方式
36
+
37
+ 临时运行:
38
+
39
+ ```bash
40
+ npx codex-id help
41
+ npx codex-id list
42
+ ```
43
+
44
+ 全局安装后运行:
45
+
46
+ ```bash
47
+ npm install -g codex-id
48
+ cid help
49
+ ```
50
+
51
+ 本地 clone 后运行:
52
+
53
+ ```bash
54
+ node ./bin/cid help
55
+ ./bin/cid help
56
+ ```
57
+
58
+ ## 多端范围
59
+
60
+ Node CLI 支持以下终端环境:
61
+
62
+ - macOS
63
+ - Linux
64
+ - WSL
65
+ - Windows Git Bash
66
+ - Windows cmd
67
+ - Windows PowerShell
68
+
69
+ 运行要求:
70
+
71
+ - Node.js 18+
72
+ - 已安装或可定位 `codex`
73
+
74
+ ## 用法
75
+
76
+ 初始化本机已有 Codex 登录态:
77
+
78
+ ```bash
79
+ cid init
80
+ # 或
81
+ cid i
82
+ ```
83
+
84
+ `init` 会先检查基础环境:
85
+
86
+ - `codex` 可执行文件可找到
87
+ - `~/.codex/auth.json` 存在、可读、不是符号链接
88
+ - `~/.codex/` 可写,`~/.codex/codex-id.json` 不是符号链接
89
+
90
+ 检查通过后,CLI 会从当前 `~/.codex/auth.json` 解析邮箱;如果没有邮箱,
91
+ 则改用 `account_id` 前 8 位,并同步到账号库:
92
+
93
+ ```bash
94
+ ~/.codex/codex-id.json
95
+ ```
96
+
97
+ 登录账号:
98
+
99
+ ```bash
100
+ cid add
101
+ ```
102
+
103
+ `add` 会调用 `codex login` 完成登录,并按登录态里的邮箱,或邮箱缺失时
104
+ 的 `account_id` 前 8 位写入:
105
+
106
+ ```bash
107
+ ~/.codex/codex-id.json
108
+ ```
109
+
110
+ 如果该邮箱已存在,`add` 会直接覆盖账号库里的对应 `auth`,
111
+ 不会额外保留一份新登录结果,也不会残留 `.login.*` 临时目录。
112
+
113
+ 查看账号列表:
114
+
115
+ ```bash
116
+ cid list
117
+ # 或
118
+ cid l
119
+ ```
120
+
121
+ `list` 默认会先联网查询额度信息,但不走模型生成:
122
+
123
+ - 查询额度前会检查账号库里的 `access_token`,已过期或 1 天内到期时,
124
+ 自动用 `refresh_token` 续期并回写 `~/.codex/codex-id.json`
125
+ - 如果续期的是当前生效账号,会同步更新 `~/.codex/auth.json`
126
+ - 续期失败不会伪装成功;后续探活仍会按 Usage 接口结果显示离线或未知
127
+ - 优先显示套餐、Next 短周期额度、Total 总周期额度
128
+ - 账号列直接显示完整邮箱;邮箱缺失时显示短 ID,不做截断
129
+ - 账号显示顺序与 `cid use N`、`cid remove N` 的编号解析顺序一致
130
+ - 当前账号会在编号后显示绿色 `*`,行颜色仍按账号状态显示
131
+ - 额度检测失败的账号,会直接用 Usage 接口探活
132
+ - limited 账号显示为浅黄色,cooling 账号显示为浅灰色
133
+ - 明确 401 / 403 的 offline 账号会显示为浅红色
134
+ - 网络异常等未知状态只标为未知
135
+
136
+ 本地状态检查时:
137
+
138
+ - `已登录`:账号库里有可用 `auth`
139
+ - `未登录`:账号库存在账号条目,但没有可用 `auth`
140
+ - `离线`:Usage 接口探活明确返回 401 / 403
141
+ - `未知`:网络异常、服务异常或其他无法确认的探活失败
142
+
143
+ 切换账号:
144
+
145
+ ```bash
146
+ cid use
147
+ # 或
148
+ cid u
149
+
150
+ cid use 2
151
+ # 或
152
+ cid u 2
153
+
154
+ cid use 6b17e1c8
155
+ ```
156
+
157
+ `use` 不带账号时会先查询额度:
158
+
159
+ - 当前生效账号处于 available 时,不自动切换
160
+ - 当前生效账号处于 limited、cooling 或 offline 时,才会尝试自动切换
161
+ - 触发自动切换后,会切到第一个 available 账号
162
+ - 如果列表里没有 available 账号,也不会强制切换
163
+ - 如果额度接口不可用,或当前没有 available 账号,则报错或保持不切换
164
+
165
+ 额度判定规则:
166
+
167
+ - 付费账号比较 Next 剩余额度;只要 Total 剩余额度为 0,就视为冷却账号,不参与自动切换
168
+ - 免费账号没有 Next 额度,只比较 Total 剩余额度
169
+ - 自动切换不比较当前账号和目标账号的具体百分比
170
+
171
+ `use` 带账号时会把目标账号的 `auth.json` 覆盖到:
172
+
173
+ ```bash
174
+ ~/.codex/auth.json
175
+ ```
176
+
177
+ 删除账号:
178
+
179
+ ```bash
180
+ cid remove 2
181
+ # 或
182
+ cid r 2
183
+ ```
184
+
185
+ `remove` 会删除账号库里的目标账号,并同步清理所有 `.login.*`
186
+ 临时登录目录;不会修改当前生效账号:
187
+
188
+ ```bash
189
+ ~/.codex/auth.json
190
+ ```
191
+
192
+ 删除离线账号:
193
+
194
+ ```bash
195
+ cid remove
196
+ # 或
197
+ cid r
198
+ ```
199
+
200
+ 无参 `remove` 会通过 Usage 接口探活所有已登录账号,并只提示是否删除
201
+ 明确离线(401 / 403)的账号;网络异常、服务异常等未知状态会跳过。
202
+ 账号库里没有可用 `auth` 的账号也会提示删除。确认选项:
203
+
204
+ ```text
205
+ 1:确定
206
+ 2:取消
207
+ ```
208
+
209
+ ## 环境变量
210
+
211
+ ```bash
212
+ CODEX_BIN=/path/to/codex
213
+ ```
214
+
215
+ 用于指定 `codex` 可执行文件路径。
216
+
217
+ 如果没有设置 `CODEX_BIN`,CLI 会按顺序查找:
218
+
219
+ 1. 当前 `PATH` 里的 `codex`
220
+ 2. VS Code 扩展目录里的 `~/.vscode/extensions/openai.chatgpt-*/bin/*/codex`
221
+
222
+ ```bash
223
+ NO_COLOR=1
224
+ ```
225
+
226
+ 用于关闭终端颜色输出。
package/bin/cid ADDED
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+
3
+ const commands = require('../src/commands');
4
+
5
+ function usage(output = process.stdout) {
6
+ output.write(`cid - Codex 账号切换助手
7
+
8
+ 命令:
9
+ cid init|i
10
+ cid add|a
11
+ cid list|l
12
+ cid use|u [account]
13
+ cid remove|r [account]
14
+ cid help
15
+
16
+ 说明:
17
+ account 可以是序号、邮箱或短 ID;use 不带 account 时自动选择有额度账号。
18
+ ~/.codex/codex-id.json 存账号库。
19
+ ~/.codex/auth.json 是当前生效槽位。
20
+ cid remove 不带账号时删除离线账号。
21
+ cid init 会检查基础环境,并同步当前登录态。
22
+
23
+ 环境变量:
24
+ CODEX_BIN 指定 codex 可执行文件路径
25
+ `);
26
+ }
27
+
28
+ function assertNoExtra(args, command) {
29
+ if (args.length !== 0) throw new Error(`用法:cid ${command}`);
30
+ }
31
+
32
+ async function main(argv = process.argv.slice(2), io = {}) {
33
+ const output = io.output || process.stdout;
34
+ const input = io.input || process.stdin;
35
+ const errOutput = io.errOutput || process.stderr;
36
+ const env = io.env || process.env;
37
+ const ALIAS = { i: 'init', l: 'list', a: 'add', u: 'use', r: 'remove', '-h': 'help', '--help': 'help' };
38
+ const [raw = 'help', ...args] = argv;
39
+ const command = ALIAS[raw] || raw;
40
+
41
+ switch (command) {
42
+ case 'init':
43
+ assertNoExtra(args, 'init');
44
+ commands.initAccounts(env, output);
45
+ break;
46
+ case 'list':
47
+ assertNoExtra(args, 'list');
48
+ await commands.listAccounts(env, output);
49
+ break;
50
+ case 'add':
51
+ assertNoExtra(args, 'add');
52
+ await commands.addAccount(env, output);
53
+ break;
54
+ case 'use':
55
+ if (args.length === 0) await commands.useDefaultAccount(env, output);
56
+ else if (args.length === 1) commands.useAccount(args[0], env, output);
57
+ else throw new Error('用法:cid use [account]');
58
+ break;
59
+ case 'remove':
60
+ if (args.length === 0) await commands.removeOfflineAccounts(env, output, input, errOutput);
61
+ else if (args.length === 1) commands.removeAccount(args[0], env, output);
62
+ else throw new Error('用法:cid remove [account]');
63
+ break;
64
+ case 'help':
65
+ usage(output);
66
+ break;
67
+ default:
68
+ process.stderr.write(`未知命令:${raw}\n`);
69
+ usage(process.stderr);
70
+ process.exitCode = 1;
71
+ }
72
+ }
73
+
74
+ main(process.argv.slice(2)).catch((error) => {
75
+ const message = error && error.message ? error.message : String(error);
76
+ console.error(`错误:${message}`);
77
+ process.exitCode = 1;
78
+ });
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "codex-id",
3
+ "version": "0.2.0",
4
+ "description": "Codex account switching CLI",
5
+ "license": "MIT",
6
+ "type": "commonjs",
7
+ "main": "./src/codex.js",
8
+ "bin": {
9
+ "cid": "bin/cid"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "src",
14
+ "README.md"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/uninto/codex-id.git"
19
+ },
20
+ "keywords": [
21
+ "codex",
22
+ "cli",
23
+ "account-switcher"
24
+ ],
25
+ "scripts": {
26
+ "test": "node --test",
27
+ "check": "node --check bin/cid && node --check src/*.js && npm test"
28
+ },
29
+ "engines": {
30
+ "node": ">=18"
31
+ }
32
+ }
@@ -0,0 +1,115 @@
1
+ const fs = require('node:fs');
2
+ const {
3
+ assertNotSymlink,
4
+ getAccountsFile,
5
+ getCodexHome,
6
+ writeFileAtomically,
7
+ } = require('./paths');
8
+ const {
9
+ decodeAccountEmailFromAuth,
10
+ decodeAccountLabel,
11
+ decodeShortAccountIdFromAuth,
12
+ } = require('./auth');
13
+
14
+ const STORE_VERSION = 1;
15
+ const SHORT_ACCOUNT_ID = /^[a-f0-9]{8}$/i;
16
+
17
+ // 校验外部传入的账号标识,避免路径穿越和隐藏目录误用。
18
+ const validateName = (name) => {
19
+ if (!name) throw new Error('缺少账号参数');
20
+ if (name === '.' || name === '..' || name.startsWith('.') || name.includes('/')) {
21
+ throw new Error('账号名不能是 .、..、以 . 开头,且不能包含 /');
22
+ }
23
+ const email = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+$/;
24
+ if (!email.test(name) && !SHORT_ACCOUNT_ID.test(name)) throw new Error('账号只能是邮箱或短 ID');
25
+ };
26
+
27
+ const displayAccount = (account) => {
28
+ return account.email || account.shortId || account.id;
29
+ };
30
+
31
+ const normalizeAccount = (auth) => {
32
+ const email = decodeAccountEmailFromAuth(auth);
33
+ const shortId = decodeShortAccountIdFromAuth(auth);
34
+ const id = email || shortId;
35
+ if (!id) throw new Error('未能从 auth.json 解析出邮箱或短 ID');
36
+ return { auth, email, id, shortId };
37
+ };
38
+
39
+ const accountMatches = (account, selector) => {
40
+ return [account.id, account.email, account.shortId, displayAccount(account)].includes(selector);
41
+ };
42
+
43
+ const readAccounts = (env = process.env) => {
44
+ const filePath = getAccountsFile(env);
45
+ const codexHome = getCodexHome(env);
46
+ if (!fs.existsSync(filePath)) return [];
47
+ assertNotSymlink(codexHome, '拒绝读取符号链接目录');
48
+ assertNotSymlink(filePath, '拒绝读取符号链接账号库');
49
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
50
+ if (!data || data.version !== STORE_VERSION || !Array.isArray(data.accounts)) {
51
+ throw new Error(`账号库格式无效:${filePath}`);
52
+ }
53
+ return data.accounts.map((auth) => normalizeAccount(auth));
54
+ };
55
+
56
+ const writeAccounts = (accounts, env = process.env) => {
57
+ const filePath = getAccountsFile(env);
58
+ const codexHome = getCodexHome(env);
59
+ if (!fs.existsSync(codexHome)) fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
60
+ assertNotSymlink(codexHome, '拒绝写入符号链接目录');
61
+ assertNotSymlink(filePath, '拒绝覆盖符号链接账号库');
62
+ const sorted = [...accounts].sort((a, b) => displayAccount(a).localeCompare(displayAccount(b), 'en'));
63
+ const payload = {
64
+ version: STORE_VERSION,
65
+ accounts: sorted.map(({ auth }) => auth),
66
+ };
67
+ writeFileAtomically(filePath, `${JSON.stringify(payload, null, 2)}\n`);
68
+ };
69
+
70
+ const upsertAccount = (auth, env = process.env) => {
71
+ const next = normalizeAccount(auth);
72
+ const current = readAccounts(env);
73
+ const overwritten = current.some((account) => account.id === next.id);
74
+ const accounts = current.filter((account) => account.id !== next.id);
75
+ writeAccounts([...accounts, next], env);
76
+ return { account: next, overwritten };
77
+ };
78
+
79
+ const removeAccountEntry = (account, env = process.env) => {
80
+ writeAccounts(readAccounts(env).filter((item) => item.id !== account.id), env);
81
+ };
82
+
83
+ const resolveAccount = (selector, env = process.env) => {
84
+ if (!selector) throw new Error('缺少账号参数');
85
+ const accounts = readAccounts(env);
86
+ if (/^[0-9]+$/.test(selector)) {
87
+ const index = Number(selector);
88
+ if (index < 1 || index > accounts.length) throw new Error(`账号序号不存在:${selector}`);
89
+ return accounts[index - 1];
90
+ }
91
+ validateName(selector);
92
+ return accounts.find((account) => accountMatches(account, selector)) || null;
93
+ };
94
+
95
+ const currentSlotLabel = (env = process.env) => {
96
+ return decodeAccountLabel(getCodexHome(env));
97
+ };
98
+
99
+ const currentAccount = (env = process.env) => {
100
+ const current = currentSlotLabel(env);
101
+ return readAccounts(env).find((account) => displayAccount(account) === current) || null;
102
+ };
103
+
104
+ module.exports = {
105
+ currentAccount,
106
+ currentSlotLabel,
107
+ displayAccount,
108
+ normalizeAccount,
109
+ readAccounts,
110
+ removeAccountEntry,
111
+ resolveAccount,
112
+ upsertAccount,
113
+ validateName,
114
+ writeAccounts,
115
+ };
package/src/auth.js ADDED
@@ -0,0 +1,57 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { assertNotSymlink } = require('./paths');
4
+
5
+ const decodeBase64Url = (value) => {
6
+ const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
7
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
8
+ return Buffer.from(padded, 'base64').toString('utf8');
9
+ };
10
+
11
+ // 读取账号 auth.json 前先校验目录和文件不是符号链接。
12
+ const readAuth = (homeDir) => {
13
+ const authPath = path.join(homeDir, 'auth.json');
14
+ if (!fs.existsSync(authPath)) return null;
15
+ assertNotSymlink(homeDir, '拒绝读取符号链接目录');
16
+ assertNotSymlink(authPath, '拒绝读取符号链接文件');
17
+ return JSON.parse(fs.readFileSync(authPath, 'utf8'));
18
+ };
19
+
20
+ const readIdTokenPayloadFromAuth = (auth) => {
21
+ const token = auth && auth.tokens && auth.tokens.id_token;
22
+ if (!token) return null;
23
+ const [, payload] = token.split('.');
24
+ if (!payload) return null;
25
+ return JSON.parse(decodeBase64Url(payload));
26
+ };
27
+
28
+ const decodeAccountEmailFromAuth = (auth) => {
29
+ try {
30
+ const decoded = readIdTokenPayloadFromAuth(auth);
31
+ return decoded && typeof decoded.email === 'string' ? decoded.email : '';
32
+ } catch (_) {
33
+ return '';
34
+ }
35
+ };
36
+
37
+ const decodeShortAccountIdFromAuth = (auth) => {
38
+ try {
39
+ const accountId = auth && auth.tokens && auth.tokens.account_id;
40
+ return typeof accountId === 'string' && accountId.length >= 8 ? accountId.slice(0, 8) : '';
41
+ } catch (_) {
42
+ return '';
43
+ }
44
+ };
45
+
46
+ // 优先展示邮箱;缺少邮箱时退回 account_id 前 8 位。
47
+ const decodeAccountLabel = (homeDir) => {
48
+ const auth = readAuth(homeDir);
49
+ return decodeAccountEmailFromAuth(auth) || decodeShortAccountIdFromAuth(auth);
50
+ };
51
+
52
+ module.exports = {
53
+ decodeAccountEmailFromAuth,
54
+ decodeAccountLabel,
55
+ decodeShortAccountIdFromAuth,
56
+ readAuth,
57
+ };
package/src/codex.js ADDED
@@ -0,0 +1,123 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { getHomeDir } = require('./paths');
4
+
5
+ const executableNames = (command) => {
6
+ return process.platform === 'win32'
7
+ ? [`${command}.cmd`, `${command}.exe`, command]
8
+ : [command];
9
+ };
10
+
11
+ // 统一判断候选文件是否可作为命令执行,兼容 Windows 的可执行判断。
12
+ const isExecutable = (filePath) => {
13
+ if (!filePath || !fs.existsSync(filePath)) return false;
14
+ if (process.platform === 'win32') return fs.statSync(filePath).isFile();
15
+ try {
16
+ fs.accessSync(filePath, fs.constants.X_OK);
17
+ return true;
18
+ } catch (_) {
19
+ return false;
20
+ }
21
+ };
22
+
23
+ const archAliases = (arch = process.arch) => {
24
+ const aliases = {
25
+ arm64: ['arm64', 'aarch64'],
26
+ ia32: ['ia32', 'x86'],
27
+ x64: ['x64', 'x86_64'],
28
+ };
29
+ return aliases[arch] || [arch];
30
+ };
31
+
32
+ const platformAliases = (platform = process.platform) => {
33
+ const aliases = {
34
+ darwin: ['darwin', 'macos'],
35
+ linux: ['linux'],
36
+ win32: ['win32', 'windows'],
37
+ };
38
+ return aliases[platform] || [platform];
39
+ };
40
+
41
+ const compatibleVscodePlatformNames = (
42
+ platform = process.platform,
43
+ arch = process.arch,
44
+ ) => {
45
+ return platformAliases(platform).flatMap((platformName) => {
46
+ return archAliases(arch).map((archName) => `${platformName}-${archName}`);
47
+ });
48
+ };
49
+
50
+ const platformNameFromExtension = (extensionName) => {
51
+ const match = extensionName.match(/^openai\.chatgpt-.+?-(.+-.+)$/);
52
+ return match ? match[1] : '';
53
+ };
54
+
55
+ const orderedVscodePlatformNames = (
56
+ extensionName,
57
+ platform = process.platform,
58
+ arch = process.arch,
59
+ ) => {
60
+ const compatibleNames = compatibleVscodePlatformNames(platform, arch);
61
+ const parsedName = platformNameFromExtension(extensionName);
62
+ return [
63
+ compatibleNames.includes(parsedName) ? parsedName : '',
64
+ ...compatibleNames,
65
+ ].filter(Boolean);
66
+ };
67
+
68
+ // 按 PATH 顺序查找命令,找到第一个可执行文件即返回。
69
+ const findOnPath = (command, env = process.env) => {
70
+ const pathValue = env.PATH || '';
71
+ for (const dir of pathValue.split(path.delimiter)) {
72
+ for (const name of executableNames(command)) {
73
+ const candidate = path.join(dir, name);
74
+ if (isExecutable(candidate)) return candidate;
75
+ }
76
+ }
77
+ return '';
78
+ };
79
+
80
+ // VS Code 插件内也可能自带 codex 二进制,作为 PATH 之外的兜底来源。
81
+ const findVscodeCodex = (env = process.env) => {
82
+ const extensionsDir = path.join(getHomeDir(env), '.vscode', 'extensions');
83
+ if (!fs.existsSync(extensionsDir)) return '';
84
+ const extensionNames = fs.readdirSync(extensionsDir).filter((name) => {
85
+ return name.startsWith('openai.chatgpt-');
86
+ });
87
+
88
+ for (const extensionName of extensionNames.reverse()) {
89
+ const binDir = path.join(extensionsDir, extensionName, 'bin');
90
+ if (!fs.existsSync(binDir)) continue;
91
+ const candidates = new Set(orderedVscodePlatformNames(extensionName));
92
+ const found = [...candidates]
93
+ .filter((platformName) => fs.existsSync(path.join(binDir, platformName)))
94
+ .flatMap((platformName) =>
95
+ executableNames('codex').map((name) => path.join(binDir, platformName, name)),
96
+ )
97
+ .find(isExecutable);
98
+ if (found) return found;
99
+ }
100
+ return '';
101
+ };
102
+
103
+ const tryFindCodexBin = (env = process.env) => {
104
+ if (env.CODEX_BIN) return isExecutable(env.CODEX_BIN) ? env.CODEX_BIN : '';
105
+ return findOnPath('codex', env) || findVscodeCodex(env);
106
+ };
107
+
108
+ const findCodexBin = (env = process.env) => {
109
+ const codexBin = tryFindCodexBin(env);
110
+ if (!codexBin) {
111
+ throw new Error('找不到 codex。请设置 CODEX_BIN=/path/to/codex,或把 codex 加到 PATH');
112
+ }
113
+ return codexBin;
114
+ };
115
+
116
+ module.exports = {
117
+ __test: {
118
+ compatibleVscodePlatformNames,
119
+ orderedVscodePlatformNames,
120
+ platformNameFromExtension,
121
+ },
122
+ findCodexBin,
123
+ };