codex-id 0.2.0 → 0.2.1
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 +45 -5
- package/bin/cid +8 -4
- package/package.json +1 -1
- package/src/accounts.js +11 -6
- package/src/auth.js +16 -2
- package/src/commands.js +50 -3
- package/src/usage.js +32 -8
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
└── codex-id.json # codex-id 账号库
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
`codex-id.json`
|
|
14
|
+
`codex-id.json` 只保存最小结构。默认账号来自 Codex 登录态:
|
|
15
15
|
|
|
16
16
|
```json
|
|
17
17
|
{
|
|
@@ -28,9 +28,26 @@
|
|
|
28
28
|
}
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
+
也可以保存手动输入的访问令牌账号:
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"version": 1,
|
|
36
|
+
"accounts": [
|
|
37
|
+
{
|
|
38
|
+
"OPENAI_API_KEY": null,
|
|
39
|
+
"email": "user@example.com",
|
|
40
|
+
"personal_access_token": "at-..."
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
31
46
|
CLI 不会打印 token。它优先从 `auth.json` 的 `id_token` payload 中解析
|
|
32
|
-
`email
|
|
33
|
-
|
|
47
|
+
`email`,手动访问令牌账号会优先使用 Usage 接口返回并保存的 `email`;
|
|
48
|
+
如果没有邮箱,再回退到 `tokens.account_id` 的前 8 位,
|
|
49
|
+
或 `personal_access_token` 后 8 位组成的
|
|
50
|
+
`pat-短标识`,用于列表显示和账号选择。
|
|
34
51
|
|
|
35
52
|
## 运行方式
|
|
36
53
|
|
|
@@ -98,15 +115,28 @@ cid i
|
|
|
98
115
|
|
|
99
116
|
```bash
|
|
100
117
|
cid add
|
|
118
|
+
# 或直接添加手动访问令牌账号
|
|
119
|
+
cid add at-...
|
|
101
120
|
```
|
|
102
121
|
|
|
103
|
-
`add`
|
|
104
|
-
|
|
122
|
+
`add` 不带参数时会调用 `codex login` 完成登录,并按登录态里的邮箱,
|
|
123
|
+
或邮箱缺失时的 `account_id` 前 8 位写入:
|
|
105
124
|
|
|
106
125
|
```bash
|
|
107
126
|
~/.codex/codex-id.json
|
|
108
127
|
```
|
|
109
128
|
|
|
129
|
+
`add` 带访问令牌时不会调用 `codex login`,会先用 Usage 额度接口验证令牌,
|
|
130
|
+
并读取接口返回的邮箱、套餐等用户信息;验证通过后直接写入:
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{
|
|
134
|
+
"OPENAI_API_KEY": null,
|
|
135
|
+
"email": "user@example.com",
|
|
136
|
+
"personal_access_token": "用户输入的访问密钥"
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
110
140
|
如果该邮箱已存在,`add` 会直接覆盖账号库里的对应 `auth`,
|
|
111
141
|
不会额外保留一份新登录结果,也不会残留 `.login.*` 临时目录。
|
|
112
142
|
|
|
@@ -174,6 +204,16 @@ cid use 6b17e1c8
|
|
|
174
204
|
~/.codex/auth.json
|
|
175
205
|
```
|
|
176
206
|
|
|
207
|
+
如果目标账号是手动访问令牌账号,写入的 `auth.json` 格式为:
|
|
208
|
+
|
|
209
|
+
```json
|
|
210
|
+
{
|
|
211
|
+
"OPENAI_API_KEY": null,
|
|
212
|
+
"email": "user@example.com",
|
|
213
|
+
"personal_access_token": "用户输入的访问密钥"
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
177
217
|
删除账号:
|
|
178
218
|
|
|
179
219
|
```bash
|
package/bin/cid
CHANGED
|
@@ -7,16 +7,17 @@ function usage(output = process.stdout) {
|
|
|
7
7
|
|
|
8
8
|
命令:
|
|
9
9
|
cid init|i
|
|
10
|
-
cid add|a
|
|
10
|
+
cid add|a [personal_access_token]
|
|
11
11
|
cid list|l
|
|
12
12
|
cid use|u [account]
|
|
13
13
|
cid remove|r [account]
|
|
14
14
|
cid help
|
|
15
15
|
|
|
16
16
|
说明:
|
|
17
|
-
account
|
|
17
|
+
account 可以是序号、邮箱、短 ID 或 pat-短标识;use 不带 account 时自动选择有额度账号。
|
|
18
18
|
~/.codex/codex-id.json 存账号库。
|
|
19
19
|
~/.codex/auth.json 是当前生效槽位。
|
|
20
|
+
cid add 不带参数时登录 Codex;带访问令牌时直接添加令牌账号。
|
|
20
21
|
cid remove 不带账号时删除离线账号。
|
|
21
22
|
cid init 会检查基础环境,并同步当前登录态。
|
|
22
23
|
|
|
@@ -48,8 +49,11 @@ async function main(argv = process.argv.slice(2), io = {}) {
|
|
|
48
49
|
await commands.listAccounts(env, output);
|
|
49
50
|
break;
|
|
50
51
|
case 'add':
|
|
51
|
-
|
|
52
|
-
await commands.
|
|
52
|
+
if (args.length === 0) await commands.addAccount(env, output);
|
|
53
|
+
else if (args.length === 1) await commands.addPersonalAccessToken(args[0], env, output);
|
|
54
|
+
else if (args.length === 2 && /^Bearer$/i.test(args[0])) {
|
|
55
|
+
await commands.addPersonalAccessToken(args.join(' '), env, output);
|
|
56
|
+
} else throw new Error('用法:cid add [personal_access_token]');
|
|
53
57
|
break;
|
|
54
58
|
case 'use':
|
|
55
59
|
if (args.length === 0) await commands.useDefaultAccount(env, output);
|
package/package.json
CHANGED
package/src/accounts.js
CHANGED
|
@@ -8,11 +8,13 @@ const {
|
|
|
8
8
|
const {
|
|
9
9
|
decodeAccountEmailFromAuth,
|
|
10
10
|
decodeAccountLabel,
|
|
11
|
+
decodePersonalAccessTokenLabelFromAuth,
|
|
11
12
|
decodeShortAccountIdFromAuth,
|
|
12
13
|
} = require('./auth');
|
|
13
14
|
|
|
14
15
|
const STORE_VERSION = 1;
|
|
15
16
|
const SHORT_ACCOUNT_ID = /^[a-f0-9]{8}$/i;
|
|
17
|
+
const PERSONAL_TOKEN_ID = /^pat-[A-Za-z0-9_-]{4,}$/;
|
|
16
18
|
|
|
17
19
|
// 校验外部传入的账号标识,避免路径穿越和隐藏目录误用。
|
|
18
20
|
const validateName = (name) => {
|
|
@@ -21,23 +23,26 @@ const validateName = (name) => {
|
|
|
21
23
|
throw new Error('账号名不能是 .、..、以 . 开头,且不能包含 /');
|
|
22
24
|
}
|
|
23
25
|
const email = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+$/;
|
|
24
|
-
if (!email.test(name) && !SHORT_ACCOUNT_ID.test(name)
|
|
26
|
+
if (!email.test(name) && !SHORT_ACCOUNT_ID.test(name) && !PERSONAL_TOKEN_ID.test(name)) {
|
|
27
|
+
throw new Error('账号只能是邮箱、短 ID 或个人访问令牌短标识');
|
|
28
|
+
}
|
|
25
29
|
};
|
|
26
30
|
|
|
27
31
|
const displayAccount = (account) => {
|
|
28
|
-
return account.email || account.shortId || account.id;
|
|
32
|
+
return account.email || account.shortId || account.tokenId || account.id;
|
|
29
33
|
};
|
|
30
34
|
|
|
31
35
|
const normalizeAccount = (auth) => {
|
|
32
36
|
const email = decodeAccountEmailFromAuth(auth);
|
|
33
37
|
const shortId = decodeShortAccountIdFromAuth(auth);
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
const tokenId = decodePersonalAccessTokenLabelFromAuth(auth);
|
|
39
|
+
const id = email || shortId || tokenId;
|
|
40
|
+
if (!id) throw new Error('未能从 auth.json 解析出邮箱、短 ID 或个人访问令牌短标识');
|
|
41
|
+
return { auth, email, id, shortId, tokenId };
|
|
37
42
|
};
|
|
38
43
|
|
|
39
44
|
const accountMatches = (account, selector) => {
|
|
40
|
-
return [account.id, account.email, account.shortId, displayAccount(account)].includes(selector);
|
|
45
|
+
return [account.id, account.email, account.shortId, account.tokenId, displayAccount(account)].includes(selector);
|
|
41
46
|
};
|
|
42
47
|
|
|
43
48
|
const readAccounts = (env = process.env) => {
|
package/src/auth.js
CHANGED
|
@@ -27,6 +27,7 @@ const readIdTokenPayloadFromAuth = (auth) => {
|
|
|
27
27
|
|
|
28
28
|
const decodeAccountEmailFromAuth = (auth) => {
|
|
29
29
|
try {
|
|
30
|
+
if (auth && typeof auth.email === 'string') return auth.email;
|
|
30
31
|
const decoded = readIdTokenPayloadFromAuth(auth);
|
|
31
32
|
return decoded && typeof decoded.email === 'string' ? decoded.email : '';
|
|
32
33
|
} catch (_) {
|
|
@@ -43,15 +44,28 @@ const decodeShortAccountIdFromAuth = (auth) => {
|
|
|
43
44
|
}
|
|
44
45
|
};
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
const decodePersonalAccessTokenLabelFromAuth = (auth) => {
|
|
48
|
+
try {
|
|
49
|
+
const token = auth && auth.personal_access_token;
|
|
50
|
+
if (typeof token !== 'string' || token.length < 8) return '';
|
|
51
|
+
return `pat-${token.slice(-8).replace(/^[-_]+/, '')}`;
|
|
52
|
+
} catch (_) {
|
|
53
|
+
return '';
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// 优先展示邮箱;缺少邮箱时退回 account_id 或 personal_access_token 短标识。
|
|
47
58
|
const decodeAccountLabel = (homeDir) => {
|
|
48
59
|
const auth = readAuth(homeDir);
|
|
49
|
-
return decodeAccountEmailFromAuth(auth)
|
|
60
|
+
return decodeAccountEmailFromAuth(auth)
|
|
61
|
+
|| decodeShortAccountIdFromAuth(auth)
|
|
62
|
+
|| decodePersonalAccessTokenLabelFromAuth(auth);
|
|
50
63
|
};
|
|
51
64
|
|
|
52
65
|
module.exports = {
|
|
53
66
|
decodeAccountEmailFromAuth,
|
|
54
67
|
decodeAccountLabel,
|
|
68
|
+
decodePersonalAccessTokenLabelFromAuth,
|
|
55
69
|
decodeShortAccountIdFromAuth,
|
|
56
70
|
readAuth,
|
|
57
71
|
};
|
package/src/commands.js
CHANGED
|
@@ -13,6 +13,7 @@ const {
|
|
|
13
13
|
currentAccount,
|
|
14
14
|
currentSlotLabel,
|
|
15
15
|
displayAccount,
|
|
16
|
+
normalizeAccount,
|
|
16
17
|
readAccounts,
|
|
17
18
|
removeAccountEntry,
|
|
18
19
|
resolveAccount,
|
|
@@ -25,6 +26,7 @@ const usage = require('./usage');
|
|
|
25
26
|
const term = require('./terminal');
|
|
26
27
|
|
|
27
28
|
const TOTAL_RESET_TIME_THRESHOLD_SECONDS = 24 * 60 * 60;
|
|
29
|
+
const PERSONAL_TOKEN_PREFIX = /^Bearer\s+/i;
|
|
28
30
|
|
|
29
31
|
// init 先做环境预检,失败时暴露真实缺失项而不是继续写账号库。
|
|
30
32
|
const runInitChecks = (env = process.env) => {
|
|
@@ -194,6 +196,25 @@ const addAccount = async (env = process.env, output = process.stdout) => {
|
|
|
194
196
|
}
|
|
195
197
|
};
|
|
196
198
|
|
|
199
|
+
const normalizePersonalAccessToken = (token) => {
|
|
200
|
+
const value = String(token || '').trim().replace(PERSONAL_TOKEN_PREFIX, '').trim();
|
|
201
|
+
if (!value) throw new Error('缺少访问令牌');
|
|
202
|
+
return value;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const addPersonalAccessToken = async (token, env = process.env, output = process.stdout, services = {}) => {
|
|
206
|
+
const personalAccessToken = normalizePersonalAccessToken(token);
|
|
207
|
+
const profile = await usage.fetchPersonalAccessTokenProfile(personalAccessToken, services.usageFetch);
|
|
208
|
+
const auth = {
|
|
209
|
+
OPENAI_API_KEY: null,
|
|
210
|
+
...(profile.email ? { email: profile.email } : {}),
|
|
211
|
+
personal_access_token: personalAccessToken,
|
|
212
|
+
};
|
|
213
|
+
const { account, overwritten } = upsertAccount(auth, env);
|
|
214
|
+
const action = overwritten ? '已覆盖已有访问令牌账号' : '已添加访问令牌账号';
|
|
215
|
+
output.write(`${action}:${displayAccount(account)}\n`);
|
|
216
|
+
};
|
|
217
|
+
|
|
197
218
|
// 当前账号进入 limited/cooling/offline 后,才尝试切到第一个 available 账号。
|
|
198
219
|
const useDefaultAccount = async (env = process.env, output = process.stdout) => {
|
|
199
220
|
const accounts = readAccounts(env);
|
|
@@ -249,11 +270,13 @@ const lightStatusLabel = (account) => {
|
|
|
249
270
|
|
|
250
271
|
// 组装列表行数据;已有 Usage 数据时不再额外探活。
|
|
251
272
|
const buildAccountRow = async (account, index, total, activeLabel, usageResults, env) => {
|
|
252
|
-
const
|
|
273
|
+
const localLabel = displayAccount(account);
|
|
274
|
+
const item = usage.usageFor(usageResults, account.id) || {};
|
|
275
|
+
const accountLabel = item.email || localLabel;
|
|
253
276
|
const key = account.id;
|
|
254
277
|
let status = lightStatusLabel(account);
|
|
255
278
|
let isOffline = false;
|
|
256
|
-
const isCurrent = Boolean(activeLabel &&
|
|
279
|
+
const isCurrent = Boolean(activeLabel && localLabel === activeLabel);
|
|
257
280
|
|
|
258
281
|
if (status === '已登录' && !usage.usageAvailableForAccount(usageResults, key)) {
|
|
259
282
|
const probeStatus = await term.withProgress(`正在探活账号 ${index}/${total}:${accountLabel}`, () => usage.probeAccountStatus(account), env);
|
|
@@ -349,6 +372,28 @@ const refreshAccountsForList = async (accounts, activeLabel, env = process.env,
|
|
|
349
372
|
return refreshed;
|
|
350
373
|
};
|
|
351
374
|
|
|
375
|
+
const syncPersonalAccessTokenEmails = (accounts, usageResults, activeLabel, env = process.env) => {
|
|
376
|
+
let activeAuth = null;
|
|
377
|
+
let changed = false;
|
|
378
|
+
const synced = accounts.map((account) => {
|
|
379
|
+
const item = usage.usageFor(usageResults, account.id);
|
|
380
|
+
if (!item || !item.email || account.email || !account.auth.personal_access_token) return account;
|
|
381
|
+
const next = normalizeAccount({ ...account.auth, email: item.email });
|
|
382
|
+
item.key = next.id;
|
|
383
|
+
changed = true;
|
|
384
|
+
if (displayAccount(account) === activeLabel) activeAuth = next.auth;
|
|
385
|
+
return next;
|
|
386
|
+
});
|
|
387
|
+
if (!changed) return accounts;
|
|
388
|
+
|
|
389
|
+
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;
|
|
395
|
+
};
|
|
396
|
+
|
|
352
397
|
const listAccounts = async (env = process.env, output = process.stdout, services = {}) => {
|
|
353
398
|
ensureDir(getCodexHome(env));
|
|
354
399
|
const activeLabel = currentSlotLabel(env);
|
|
@@ -358,8 +403,9 @@ const listAccounts = async (env = process.env, output = process.stdout, services
|
|
|
358
403
|
const usageResults = await term.withProgress('正在查询账号额度...', () => {
|
|
359
404
|
return usage.loadUsage(accounts, services.usageFetch);
|
|
360
405
|
}, env);
|
|
406
|
+
const syncedAccounts = syncPersonalAccessTokenEmails(accounts, usageResults, activeLabel, env);
|
|
361
407
|
const hasUsage = usage.hasUsageData(usageResults);
|
|
362
|
-
const rows = await loadAccountRows(
|
|
408
|
+
const rows = await loadAccountRows(syncedAccounts, activeLabel, usageResults, env);
|
|
363
409
|
const accountWidth = Math.max('Account'.length, ...rows.map((r) => r.account.length));
|
|
364
410
|
|
|
365
411
|
const header = hasUsage
|
|
@@ -377,6 +423,7 @@ const listAccounts = async (env = process.env, output = process.stdout, services
|
|
|
377
423
|
|
|
378
424
|
module.exports = {
|
|
379
425
|
addAccount,
|
|
426
|
+
addPersonalAccessToken,
|
|
380
427
|
getUsageRowColor,
|
|
381
428
|
initAccounts,
|
|
382
429
|
listAccounts,
|
package/src/usage.js
CHANGED
|
@@ -18,6 +18,12 @@ const ACCOUNT_USAGE_STATES = Object.freeze({
|
|
|
18
18
|
const extractAuthFields = (homeDir) => {
|
|
19
19
|
try {
|
|
20
20
|
const auth = typeof homeDir === 'string' ? readAuth(homeDir) : homeDir && homeDir.auth;
|
|
21
|
+
if (auth && typeof auth.personal_access_token === 'string') {
|
|
22
|
+
return {
|
|
23
|
+
accessToken: auth.personal_access_token,
|
|
24
|
+
accountId: '',
|
|
25
|
+
};
|
|
26
|
+
}
|
|
21
27
|
const tokens = auth && auth.tokens;
|
|
22
28
|
if (!tokens || typeof tokens.access_token !== 'string' || typeof tokens.account_id !== 'string') {
|
|
23
29
|
return null;
|
|
@@ -51,6 +57,12 @@ const hasUsageFields = (item) => {
|
|
|
51
57
|
));
|
|
52
58
|
};
|
|
53
59
|
|
|
60
|
+
const buildUsageHeaders = (token, accountId = '') => {
|
|
61
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
62
|
+
if (accountId) headers['ChatGPT-Account-Id'] = accountId;
|
|
63
|
+
return headers;
|
|
64
|
+
};
|
|
65
|
+
|
|
54
66
|
// 将账号条目转换成可并发查询 Usage 的请求条目。
|
|
55
67
|
const buildUsageEntries = (accountDirs) => {
|
|
56
68
|
return accountDirs.flatMap((account) => {
|
|
@@ -78,10 +90,7 @@ const findTotalWindow = (windows) => {
|
|
|
78
90
|
const fetchUsageOne = async (entry, fetchImpl = fetch) => {
|
|
79
91
|
try {
|
|
80
92
|
const response = await fetchImpl(USAGE_ENDPOINT, {
|
|
81
|
-
headers:
|
|
82
|
-
Authorization: `Bearer ${entry.token}`,
|
|
83
|
-
'ChatGPT-Account-Id': entry.accountId,
|
|
84
|
-
},
|
|
93
|
+
headers: buildUsageHeaders(entry.token, entry.accountId),
|
|
85
94
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
86
95
|
});
|
|
87
96
|
if (!response.ok) return { key: entry.key, error: response.status };
|
|
@@ -94,6 +103,7 @@ const fetchUsageOne = async (entry, fetchImpl = fetch) => {
|
|
|
94
103
|
const totalUsed = normalizePercent(total.used_percent);
|
|
95
104
|
return {
|
|
96
105
|
key: entry.key,
|
|
106
|
+
email: data.email || '',
|
|
97
107
|
plan: data.plan_type || '',
|
|
98
108
|
next_used: nextUsed,
|
|
99
109
|
next_reset: next.reset_at ?? null,
|
|
@@ -118,10 +128,7 @@ const probeAccountStatus = async (homeDir, fetchImpl = fetch) => {
|
|
|
118
128
|
if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return 'unknown';
|
|
119
129
|
try {
|
|
120
130
|
const response = await fetchImpl(USAGE_ENDPOINT, {
|
|
121
|
-
headers:
|
|
122
|
-
Authorization: `Bearer ${fields.accessToken}`,
|
|
123
|
-
'ChatGPT-Account-Id': fields.accountId,
|
|
124
|
-
},
|
|
131
|
+
headers: buildUsageHeaders(fields.accessToken, fields.accountId),
|
|
125
132
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
126
133
|
});
|
|
127
134
|
if (response.ok) return 'online';
|
|
@@ -132,6 +139,22 @@ const probeAccountStatus = async (homeDir, fetchImpl = fetch) => {
|
|
|
132
139
|
}
|
|
133
140
|
};
|
|
134
141
|
|
|
142
|
+
const fetchPersonalAccessTokenProfile = async (token, fetchImpl = fetch) => {
|
|
143
|
+
if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') {
|
|
144
|
+
throw new Error('当前 Node 运行时不支持访问令牌验证');
|
|
145
|
+
}
|
|
146
|
+
const response = await fetchImpl(USAGE_ENDPOINT, {
|
|
147
|
+
headers: buildUsageHeaders(token),
|
|
148
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
149
|
+
});
|
|
150
|
+
if (!response.ok) throw new Error(`访问令牌验证失败:${response.status}`);
|
|
151
|
+
const data = await response.json();
|
|
152
|
+
return {
|
|
153
|
+
email: data.email || '',
|
|
154
|
+
plan: data.plan_type || '',
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
|
|
135
158
|
const loadUsage = async (accountDirs, fetchImpl = fetch) => {
|
|
136
159
|
if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return [];
|
|
137
160
|
const entries = buildUsageEntries(accountDirs);
|
|
@@ -188,6 +211,7 @@ module.exports = {
|
|
|
188
211
|
ACCOUNT_USAGE_STATES,
|
|
189
212
|
accountIsAvailableForAutoSwitch,
|
|
190
213
|
accountShouldAutoSwitch,
|
|
214
|
+
fetchPersonalAccessTokenProfile,
|
|
191
215
|
getAccountUsageState,
|
|
192
216
|
hasUsageData,
|
|
193
217
|
loadUsage,
|