dsh-codex-credit-hub 1.0.0 → 1.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 +10 -5
- package/client.js +20 -7
- package/index.js +668 -82
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/openai-sync.inc.js +165 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -13,10 +13,12 @@ DeepSeek Harness 扩展插件,在左侧边栏底部、头像上方显示 **Cod
|
|
|
13
13
|
### Codex API
|
|
14
14
|
|
|
15
15
|
- **只使用 OpenAI Platform 登录态,不接受、不读取、不保存 API Key。**
|
|
16
|
-
-
|
|
16
|
+
- **优先复用 Ego Lite**:如果本机安装了 Ego Lite 且已登录 `platform.openai.com`,自动读取其 Platform OAuth 登录态。
|
|
17
|
+
- **没有 Ego Lite 也能用**:自动检测系统 Chrome / Edge / Brave / Chromium,打开插件专用登录窗口;登录成功后自动捕获令牌并关闭窗口,不读取或接管日常浏览器配置目录。
|
|
18
|
+
- **后续纯后台续期**:保存 Platform OAuth 访问令牌(约 10 天)和刷新令牌后,后台直接调用 OpenAI OAuth 续期、`onboarding/login` 会话兑换和 `credit_grants` 余额查询,不再为每次刷新打开浏览器。
|
|
17
19
|
- 展示与 `https://platform.openai.com/home` 一致的真实余额、总额度、已用额度、剩余百分比和最近 grant 到期时间。
|
|
18
|
-
-
|
|
19
|
-
- 临时会话只保存到 DSH
|
|
20
|
+
- 会话过期时优先在后台续期;只有刷新令牌失效或首次连接时,才需要用户主动点击「同步 OpenAI 登录态」。
|
|
21
|
+
- 临时会话只保存到 DSH 凭证库,不返回给界面或 Agent 工具;默认本地凭证文件在 POSIX 系统仅当前 OS 用户可读,但并非加密存储。卸载插件会取消同步并丢弃内存状态;删除凭证请在 DSH 凭证管理中操作。
|
|
20
22
|
|
|
21
23
|
### Agent 工具
|
|
22
24
|
|
|
@@ -48,7 +50,7 @@ dsh-codex-credit-hub
|
|
|
48
50
|
指定版本安装(避免包管理器的最新版本观察期影响):
|
|
49
51
|
|
|
50
52
|
```text
|
|
51
|
-
dsh-codex-credit-hub@1.
|
|
53
|
+
dsh-codex-credit-hub@1.2.0
|
|
52
54
|
```
|
|
53
55
|
|
|
54
56
|
### 本地目录安装
|
|
@@ -64,6 +66,9 @@ dsh-codex-credit-hub@1.0.0
|
|
|
64
66
|
|
|
65
67
|
## 运行前提与限制
|
|
66
68
|
|
|
67
|
-
-
|
|
69
|
+
- 首次连接 OpenAI Platform 需要一个可登录的浏览器:优先使用 Ego Lite;没有时使用系统 Chrome / Edge / Brave / Chromium 的插件专用窗口。
|
|
70
|
+
- 插件不会读取 Safari 或日常 Chrome 的本地数据目录,也不会要求用户手动复制 `sess-...` 或 API Key。
|
|
71
|
+
- 系统浏览器登录使用独立目录 `<DSH_HOME>/codex-credit-hub-browser`,其中可能保存 OpenAI 登录 Cookie;删除该目录即可清除这套专用浏览器登录状态。
|
|
72
|
+
- 日常刷新依赖 DSH 凭证库中的 OAuth 刷新令牌;默认本地凭证文件在 POSIX 系统仅当前 OS 用户可读,并非加密存储。撤销 OpenAI 登录或删除该凭证后,需要重新连接。
|
|
68
73
|
- OpenAI Platform 的 `onboarding/login` 和 `credit_grants` 属于网页端接口,不是 OpenAI 面向普通 API Key 的公开余额 API;如果 OpenAI 调整接口,插件会显示同步失败并保留手动重试入口。
|
|
69
74
|
- Codex 订阅额度与 OpenAI API 预付/赠送余额是不同账户体系,插件分别展示,不互相推算。
|
package/client.js
CHANGED
|
@@ -29,7 +29,8 @@ window.__ModuleLoader__.load({
|
|
|
29
29
|
nextExpiry: 'Next Expiry', updated: 'Updated', refresh: 'Refresh', refreshing: 'Refreshing…',
|
|
30
30
|
manage: 'Manage usage', close: 'Close quota details', error: 'Unable to load Codex quota', retry: 'Try again',
|
|
31
31
|
syncBrowser: 'Sync OpenAI login', syncingBrowser: 'Syncing…',
|
|
32
|
-
|
|
32
|
+
stale: 'Showing the last successful balance; retrying in the background.',
|
|
33
|
+
apiHint: 'Uses Ego Lite when available, or opens a dedicated Chrome / Edge login window once. Later refreshes run in the background. No API key is required.',
|
|
33
34
|
cliHint: 'Reads ~/.codex/auth.json (read-only) or `codex app-server`. Run `codex login` in terminal to sign in.',
|
|
34
35
|
}
|
|
35
36
|
const zh = {
|
|
@@ -42,7 +43,8 @@ window.__ModuleLoader__.load({
|
|
|
42
43
|
nextExpiry: '最近到期', updated: '更新于', refresh: '刷新', refreshing: '刷新中…',
|
|
43
44
|
manage: '管理用量', close: '关闭额度详情', error: '暂时无法读取 Codex 额度', retry: '重试',
|
|
44
45
|
syncBrowser: '同步 OpenAI 登录态', syncingBrowser: '同步中…',
|
|
45
|
-
|
|
46
|
+
stale: '显示上次成功读取的余额,后台正在自动重试。',
|
|
47
|
+
apiHint: '优先复用 Ego Lite;没有时会用系统 Chrome / Edge 打开一次专用登录窗口。后续在后台自动续期,无需输入 API Key。',
|
|
46
48
|
cliHint: '自动只读读取 ~/.codex/auth.json 或 codex app-server;若未登录请在终端执行 `codex login`。',
|
|
47
49
|
}
|
|
48
50
|
|
|
@@ -60,7 +62,7 @@ window.__ModuleLoader__.load({
|
|
|
60
62
|
const schedule = (state) => {
|
|
61
63
|
if (disposed) return
|
|
62
64
|
if (timer !== null) clearTimeout(timer)
|
|
63
|
-
const seconds = state?.preferences?.refreshIntervalSec ?? 60
|
|
65
|
+
const seconds = state?.retryAfterSec ?? state?.preferences?.refreshIntervalSec ?? 60
|
|
64
66
|
timer = setTimeout(() => { void load(false) }, Math.max(15, seconds) * 1000)
|
|
65
67
|
}
|
|
66
68
|
const load = async (force = false) => {
|
|
@@ -84,8 +86,18 @@ window.__ModuleLoader__.load({
|
|
|
84
86
|
}
|
|
85
87
|
const mutate = async (mutEndpoint, payload) => {
|
|
86
88
|
const current = ++generation
|
|
89
|
+
const previous = snapshot
|
|
90
|
+
emit({ ...snapshot, error: undefined })
|
|
87
91
|
const result = await callApi(mutEndpoint, payload)
|
|
88
|
-
if (!result.ok)
|
|
92
|
+
if (!result.ok) {
|
|
93
|
+
const message = result.error.message
|
|
94
|
+
if (!disposed && current === generation) {
|
|
95
|
+
const next = previous.status === 'ok' ? { ...previous, error: message } : { ...previous, status: previous.status === 'unauthorized' ? 'unauthorized' : 'error', error: message }
|
|
96
|
+
emit(next)
|
|
97
|
+
schedule(next)
|
|
98
|
+
}
|
|
99
|
+
throw new Error(message)
|
|
100
|
+
}
|
|
89
101
|
if (disposed || current !== generation) return result.value
|
|
90
102
|
emit(result.value); schedule(result.value)
|
|
91
103
|
return result.value
|
|
@@ -227,15 +239,16 @@ window.__ModuleLoader__.load({
|
|
|
227
239
|
h('div', null, h('div', { className: 'cxh-factLabel' }, t('totalUsed')), h('div', { className: 'cxh-factValue' }, formatUsd(quota.totalUsedUsd))),
|
|
228
240
|
nextExpiry && h('div', null, h('div', { className: 'cxh-factLabel' }, t('nextExpiry')), h('div', { className: 'cxh-factValue' }, formatResetTime(nextExpiry.expiresAtMs)))),
|
|
229
241
|
h('div', { className: 'cxh-footer' }, h('span', { className: 'cxh-updated' }, `${t('updated')} ${updated}`), h('div', { className: 'cxh-footerActions' }, syncButton, h('button', { type: 'button', className: 'cxh-refresh', disabled: busy !== '', onClick: refresh }, h(RefreshIcon), busy === 'refresh' ? t('refreshing') : t('refresh'))))),
|
|
230
|
-
quota && state.
|
|
242
|
+
quota && state.stale && h('p', { className: 'cxh-help', role: 'status' }, t('stale')),
|
|
243
|
+
quota && state.error && !actionError && h('p', { className: 'cxh-error', role: 'status' }, state.error),
|
|
231
244
|
!quota && state.status === 'loading' && h('div', { className: 'cxh-loading' }, t('loading')),
|
|
232
|
-
!quota && state.status !== 'loading' && h('p', { className: state.status === 'unauthorized' ? 'cxh-help' : 'cxh-error', role: 'status' }, state.error || t('error')),
|
|
245
|
+
!quota && state.status !== 'loading' && !actionError && h('p', { className: state.status === 'unauthorized' ? 'cxh-help' : 'cxh-error', role: 'status' }, state.error || t('error')),
|
|
233
246
|
actionError && h('p', { className: 'cxh-error', role: 'status' }, actionError),
|
|
234
247
|
!quota && state.status !== 'loading' && h('p', { className: 'cxh-help' }, isCli ? t('cliHint') : t('apiHint')),
|
|
235
248
|
!quota && state.status !== 'loading' && h('div', { className: 'cxh-errorActions' }, isCli
|
|
236
249
|
? h('button', { type: 'button', className: 'cxh-retry', disabled: busy !== '', onClick: refresh }, busy === 'refresh' ? t('refreshing') : t('retry'))
|
|
237
250
|
: h('button', { type: 'button', className: 'cxh-primary', disabled: busy !== '', onClick: sync }, busy === 'sync' ? t('syncingBrowser') : t('syncBrowser'))),
|
|
238
|
-
h('button', { type: 'button', className: 'cxh-manage', onClick: manage }, h('span', null, t('manage')), h('span', { 'aria-hidden': true }, '↗')),
|
|
251
|
+
quota && h('button', { type: 'button', className: 'cxh-manage', onClick: manage }, h('span', null, t('manage')), h('span', { 'aria-hidden': true }, '↗')),
|
|
239
252
|
), document.body),
|
|
240
253
|
)
|
|
241
254
|
}
|
package/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
|
-
import {
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
3
|
+
import { mkdir, readFile, rm } from 'node:fs/promises'
|
|
3
4
|
import { homedir } from 'node:os'
|
|
4
5
|
import { delimiter, join } from 'node:path'
|
|
6
|
+
import { randomUUID } from 'node:crypto'
|
|
5
7
|
import z from '@deepseek-ai/schemastery'
|
|
6
8
|
import { credentialKey } from '@deepseek-ai/dsh-credentials'
|
|
7
9
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
@@ -15,6 +17,10 @@ export const RECORD_ID_API = 'codex-api'
|
|
|
15
17
|
const CODEX_WHAM_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'
|
|
16
18
|
const CODEX_WEB_URL = 'https://chatgpt.com/codex/settings/usage'
|
|
17
19
|
const OPENAI_CREDIT_GRANTS_URL = 'https://api.openai.com/v1/dashboard/billing/credit_grants'
|
|
20
|
+
const OPENAI_ONBOARDING_LOGIN_URL = 'https://api.openai.com/v1/dashboard/onboarding/login'
|
|
21
|
+
const OPENAI_OAUTH_TOKEN_URL = 'https://auth.openai.com/api/accounts/oauth/token'
|
|
22
|
+
const OPENAI_PLATFORM_CLIENT_ID = 'app_2SKx67EdpoN0G6j64rFvigXD'
|
|
23
|
+
const OPENAI_PLATFORM_RESOURCE = 'https://api.openai.com/v1'
|
|
18
24
|
const OPENAI_API_WEB_URL = 'https://platform.openai.com/home'
|
|
19
25
|
const OPENAI_PLATFORM_HOME_URL = 'https://platform.openai.com/home'
|
|
20
26
|
const OPENAI_BROWSER_SYNC_COOLDOWN_MS = 60_000
|
|
@@ -83,10 +89,14 @@ export function isJwtExpired(token, skewMs = 60_000) {
|
|
|
83
89
|
}
|
|
84
90
|
|
|
85
91
|
function requestFailure(error, label) {
|
|
92
|
+
if (error?.name === 'TimeoutError') {
|
|
93
|
+
return { ok: false, status: 0, network: true, message: `${label} 网络请求超时,请检查网络或代理连接` }
|
|
94
|
+
}
|
|
86
95
|
if (error?.name === 'AbortError') return { ok: false, status: 0, message: `${label} 请求已取消` }
|
|
87
96
|
return {
|
|
88
97
|
ok: false,
|
|
89
98
|
status: 0,
|
|
99
|
+
network: true,
|
|
90
100
|
message: scrubSecrets(`${label} 网络请求失败,请检查网络或代理连接 (${error instanceof Error ? error.message : String(error)})`),
|
|
91
101
|
}
|
|
92
102
|
}
|
|
@@ -447,6 +457,13 @@ async function fetchOpenAiCreditBalance(sessionKey, organizationId = '', signal)
|
|
|
447
457
|
const message = body?.error?.message || body?.message || ('OpenAI Billing 请求失败 (HTTP ' + response.status + ')')
|
|
448
458
|
return { ok: false, status: response.status, message: scrubSecrets(message) }
|
|
449
459
|
}
|
|
460
|
+
return await fetchOpenAiCreditBalanceFromBody(body, organizationId)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function fetchOpenAiCreditBalanceFromBody(body, organizationId = '') {
|
|
464
|
+
if (!body || typeof body !== 'object') {
|
|
465
|
+
return { ok: false, status: 502, message: 'OpenAI Billing 返回了空响应' }
|
|
466
|
+
}
|
|
450
467
|
if (body.object && body.object !== 'credit_summary') {
|
|
451
468
|
return { ok: false, status: 502, message: 'OpenAI Billing 返回了无法识别的响应格式' }
|
|
452
469
|
}
|
|
@@ -503,49 +520,14 @@ async function fetchOpenAiCreditBalance(sessionKey, organizationId = '', signal)
|
|
|
503
520
|
let openAiBrowserSyncInFlight = null
|
|
504
521
|
let openAiBrowserSyncLastAttempt = 0
|
|
505
522
|
let openAiBrowserSyncLastError = ''
|
|
523
|
+
let openAiBrowserSyncLastErrorCode = ''
|
|
524
|
+
let openAiLoginPending = null
|
|
525
|
+
const OPENAI_SYNC_SCRIPT = readFileSync(new URL('./openai-sync.inc.js', import.meta.url), 'utf8')
|
|
506
526
|
|
|
507
|
-
async function syncOpenAiSessionFromEgoBrowserOnce(signal) {
|
|
527
|
+
async function syncOpenAiSessionFromEgoBrowserOnce(signal, allowHandoff = false) {
|
|
508
528
|
return await new Promise((resolve) => {
|
|
509
|
-
const script =
|
|
510
|
-
|
|
511
|
-
const page = task.page("p1");
|
|
512
|
-
let result = { sessionKey: null, organizationId: "", email: "" };
|
|
513
|
-
try {
|
|
514
|
-
await page.cdp("Network.enable");
|
|
515
|
-
await page.goto(${JSON.stringify(OPENAI_PLATFORM_HOME_URL)}, { timeout: 25000 });
|
|
516
|
-
await page.waitForTimeout(3500);
|
|
517
|
-
const events = await page.events();
|
|
518
|
-
for (const event of events) {
|
|
519
|
-
if (event.method !== "Network.requestWillBeSent") continue;
|
|
520
|
-
const params = event.params || {};
|
|
521
|
-
if (!(params.request?.url || "").includes("/v1/dashboard/onboarding/login")) continue;
|
|
522
|
-
try {
|
|
523
|
-
const response = await page.cdp("Network.getResponseBody", { requestId: params.requestId });
|
|
524
|
-
const parsed = JSON.parse(response.body || "{}");
|
|
525
|
-
const session = parsed?.user?.session?.sensitive_id;
|
|
526
|
-
if (!session) continue;
|
|
527
|
-
const orgs = Array.isArray(parsed?.user?.orgs?.data) ? parsed.user.orgs.data : [];
|
|
528
|
-
const org = orgs.find(item => item.personal) || orgs[0];
|
|
529
|
-
result = {
|
|
530
|
-
sessionKey: session,
|
|
531
|
-
organizationId: org?.id || "",
|
|
532
|
-
email: parsed?.user?.email || "",
|
|
533
|
-
};
|
|
534
|
-
} catch {}
|
|
535
|
-
}
|
|
536
|
-
if (!result.sessionKey) {
|
|
537
|
-
const text = await page.evaluate(() => document.body?.innerText || "").catch(() => "");
|
|
538
|
-
result.error = /log in|sign in|登录/i.test(text)
|
|
539
|
-
? "未检测到 OpenAI Platform 登录态,请先在浏览器登录 platform.openai.com"
|
|
540
|
-
: "未能从 OpenAI Platform 页面获取会话,请确认页面已登录后重试";
|
|
541
|
-
}
|
|
542
|
-
} catch (error) {
|
|
543
|
-
result.error = String(error?.message || error);
|
|
544
|
-
} finally {
|
|
545
|
-
await task.finish({ keep: [] }).catch(() => {});
|
|
546
|
-
}
|
|
547
|
-
console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
|
548
|
-
`
|
|
529
|
+
const script = OPENAI_SYNC_SCRIPT.replace('__ALLOW_HANDOFF__', allowHandoff ? 'true' : 'false')
|
|
530
|
+
|
|
549
531
|
const envPath = [
|
|
550
532
|
process.env.PATH ?? '',
|
|
551
533
|
'/usr/local/bin',
|
|
@@ -562,7 +544,6 @@ console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
|
|
562
544
|
let stdout = ''
|
|
563
545
|
let stderr = ''
|
|
564
546
|
let settled = false
|
|
565
|
-
let timer = null
|
|
566
547
|
const finish = (value) => {
|
|
567
548
|
if (settled) return
|
|
568
549
|
settled = true
|
|
@@ -579,33 +560,35 @@ console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
|
|
579
560
|
return
|
|
580
561
|
}
|
|
581
562
|
signal?.addEventListener('abort', onAbort, { once: true })
|
|
582
|
-
timer = setTimeout(() => {
|
|
563
|
+
const timer = setTimeout(() => {
|
|
583
564
|
try { child.kill('SIGKILL') } catch {}
|
|
584
|
-
finish({ error: 'OpenAI 浏览器同步超时(
|
|
585
|
-
},
|
|
565
|
+
finish({ error: 'OpenAI 浏览器同步超时(65 秒),请检查网络或代理后重试' })
|
|
566
|
+
}, 65_000)
|
|
586
567
|
timer.unref?.()
|
|
587
568
|
child.stdout.on('data', chunk => { stdout += chunk.toString('utf8') })
|
|
588
569
|
child.stderr.on('data', chunk => { stderr += chunk.toString('utf8') })
|
|
589
570
|
child.on('error', error => {
|
|
590
571
|
finish({
|
|
572
|
+
code: error?.code === 'ENOENT' ? 'no-ego-browser' : 'ego-launch-failed',
|
|
591
573
|
error: error?.code === 'ENOENT'
|
|
592
|
-
? '未检测到 ego-browser
|
|
593
|
-
: scrubSecrets(
|
|
574
|
+
? '未检测到 Ego Lite / ego-browser'
|
|
575
|
+
: scrubSecrets('无法启动 Ego Lite: ' + error.message),
|
|
594
576
|
})
|
|
595
577
|
})
|
|
596
578
|
child.on('close', () => {
|
|
597
579
|
const output = `${stdout}\n${stderr}`
|
|
598
580
|
const marker = output.lastIndexOf('__CODEX_OPENAI_SYNC__')
|
|
599
581
|
if (marker < 0) {
|
|
600
|
-
finish({ error: 'OpenAI
|
|
582
|
+
finish({ error: 'OpenAI 浏览器同步未完成,请确认 Ego Lite 已启动并可访问 platform.openai.com' })
|
|
601
583
|
return
|
|
602
584
|
}
|
|
603
585
|
try {
|
|
604
586
|
const jsonText = output.slice(marker + '__CODEX_OPENAI_SYNC__'.length).trim().split('\n')[0]
|
|
605
587
|
const parsed = JSON.parse(jsonText)
|
|
588
|
+
if (parsed?.error) parsed.error = scrubSecrets(parsed.error)
|
|
606
589
|
finish(parsed)
|
|
607
590
|
} catch {
|
|
608
|
-
finish({ error: 'OpenAI
|
|
591
|
+
finish({ error: 'OpenAI 浏览器同步返回格式异常,请重试' })
|
|
609
592
|
}
|
|
610
593
|
})
|
|
611
594
|
})
|
|
@@ -653,25 +636,456 @@ function subscribeOpenAiBrowserSync(entry, signal) {
|
|
|
653
636
|
})
|
|
654
637
|
}
|
|
655
638
|
|
|
656
|
-
|
|
639
|
+
const OPENAI_OAUTH_EXPIRY_MARGIN_MS = 3 * 60 * 1000
|
|
640
|
+
const OPENAI_PLATFORM_AUTH_KEY = 'oai-auth:onboard'
|
|
641
|
+
|
|
642
|
+
function decodeJwtExpMs(token) {
|
|
643
|
+
const payload = decodeJwtPayload(token)
|
|
644
|
+
const exp = Number(payload?.exp ?? 0)
|
|
645
|
+
if (!Number.isFinite(exp) || exp <= 0) return 0
|
|
646
|
+
return exp > 1e12 ? exp : exp * 1000
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function isTokenUsable(token, expiresAtMs = 0, skewMs = OPENAI_OAUTH_EXPIRY_MARGIN_MS) {
|
|
650
|
+
if (typeof token !== 'string' || !token.trim()) return false
|
|
651
|
+
const effectiveExp = expiresAtMs > 0 ? expiresAtMs : decodeJwtExpMs(token)
|
|
652
|
+
if (!effectiveExp) return !isJwtExpired(token, skewMs)
|
|
653
|
+
return Date.now() + skewMs < effectiveExp
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
async function exchangeOpenAiAccessTokenForSession(accessToken, signal) {
|
|
657
|
+
const token = normalizeSecretInput(accessToken)
|
|
658
|
+
if (!token) {
|
|
659
|
+
return { ok: false, status: 401, code: 'login-required', message: '缺少 OpenAI Platform 访问令牌,请重新同步' }
|
|
660
|
+
}
|
|
661
|
+
const result = await fetchJson(OPENAI_ONBOARDING_LOGIN_URL, {
|
|
662
|
+
method: 'POST',
|
|
663
|
+
headers: {
|
|
664
|
+
Authorization: `Bearer ${token}`,
|
|
665
|
+
'Content-Type': 'application/json',
|
|
666
|
+
Accept: 'application/json',
|
|
667
|
+
},
|
|
668
|
+
body: '{}',
|
|
669
|
+
signal: combineSignals(signal, 12_000),
|
|
670
|
+
}, 'OpenAI Onboarding')
|
|
671
|
+
if (result.error) return result.error
|
|
672
|
+
const { response, body, html } = result
|
|
673
|
+
if (html || response.status === 401 || response.status === 403) {
|
|
674
|
+
return { ok: false, status: 401, code: 'login-required', message: 'OpenAI Platform 访问令牌已失效,请重新同步' }
|
|
675
|
+
}
|
|
676
|
+
if (!response.ok || !body || typeof body !== 'object') {
|
|
677
|
+
const message = body?.error?.message || body?.message || ('OpenAI 登录态兑换失败 (HTTP ' + response.status + ')')
|
|
678
|
+
return { ok: false, status: response.status, message: scrubSecrets(message) }
|
|
679
|
+
}
|
|
680
|
+
const sessionKey = normalizeSecretInput(body?.user?.session?.sensitive_id)
|
|
681
|
+
if (!sessionKey.startsWith('sess-')) {
|
|
682
|
+
return { ok: false, status: 502, code: 'session-missing', message: 'OpenAI 登录态兑换未返回有效会话' }
|
|
683
|
+
}
|
|
684
|
+
const orgs = Array.isArray(body?.user?.orgs?.data) ? body.user.orgs.data : []
|
|
685
|
+
const org = orgs.find(item => item.personal) || orgs[0]
|
|
686
|
+
return {
|
|
687
|
+
ok: true,
|
|
688
|
+
sessionKey,
|
|
689
|
+
organizationId: typeof org?.id === 'string' ? org.id.trim() : '',
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async function refreshOpenAiPlatformOAuthToken(refreshToken, deviceId = '', signal) {
|
|
694
|
+
const token = normalizeSecretInput(refreshToken)
|
|
695
|
+
if (!token) {
|
|
696
|
+
return { ok: false, status: 401, code: 'login-required', message: '缺少 OpenAI Platform 刷新令牌,请重新同步' }
|
|
697
|
+
}
|
|
698
|
+
const headers = {
|
|
699
|
+
'Content-Type': 'application/json',
|
|
700
|
+
Accept: 'application/json',
|
|
701
|
+
}
|
|
702
|
+
if (deviceId) headers['oai-did'] = deviceId
|
|
703
|
+
const result = await fetchJson(OPENAI_OAUTH_TOKEN_URL, {
|
|
704
|
+
method: 'POST',
|
|
705
|
+
headers,
|
|
706
|
+
body: JSON.stringify({
|
|
707
|
+
client_id: OPENAI_PLATFORM_CLIENT_ID,
|
|
708
|
+
refresh_token: token,
|
|
709
|
+
grant_type: 'refresh_token',
|
|
710
|
+
resource: OPENAI_PLATFORM_RESOURCE,
|
|
711
|
+
}),
|
|
712
|
+
signal: combineSignals(signal, 12_000),
|
|
713
|
+
}, 'OpenAI OAuth')
|
|
714
|
+
if (result.error) return result.error
|
|
715
|
+
const { response, body, html } = result
|
|
716
|
+
if (html) {
|
|
717
|
+
return { ok: false, status: 502, network: true, message: 'OpenAI OAuth 返回了非 JSON 页面响应' }
|
|
718
|
+
}
|
|
719
|
+
if (response.status === 400 || response.status === 401 || response.status === 403) {
|
|
720
|
+
const oauthErr = typeof body?.error === 'string' ? body.error : body?.error?.code
|
|
721
|
+
const terminal = oauthErr === 'invalid_grant' || oauthErr === 'unauthorized_client' || oauthErr === 'invalid_client' || response.status === 401 || response.status === 403
|
|
722
|
+
const msg = body?.error_description || body?.error?.message || body?.error || ('OpenAI OAuth 续期失败 (HTTP ' + response.status + ')')
|
|
723
|
+
return {
|
|
724
|
+
ok: false,
|
|
725
|
+
status: terminal ? 401 : response.status,
|
|
726
|
+
code: terminal ? 'login-required' : 'oauth-refresh-failed',
|
|
727
|
+
message: scrubSecrets(msg),
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (!response.ok || !body || typeof body !== 'object') {
|
|
731
|
+
const message = body?.error_description || body?.error?.message || ('OpenAI OAuth 续期失败 (HTTP ' + response.status + ')')
|
|
732
|
+
return { ok: false, status: response.status, message: scrubSecrets(message) }
|
|
733
|
+
}
|
|
734
|
+
const accessToken = normalizeSecretInput(body.access_token)
|
|
735
|
+
const nextRefreshToken = normalizeSecretInput(body.refresh_token) || token
|
|
736
|
+
if (!accessToken) {
|
|
737
|
+
return { ok: false, status: 502, message: 'OpenAI OAuth 续期未返回访问令牌' }
|
|
738
|
+
}
|
|
739
|
+
const expiresInSec = parseOptionalFiniteNumber(body.expires_in)
|
|
740
|
+
const accessExpiresAt = decodeJwtExpMs(accessToken) || (expiresInSec ? Date.now() + expiresInSec * 1000 : 0)
|
|
741
|
+
return {
|
|
742
|
+
ok: true,
|
|
743
|
+
accessToken,
|
|
744
|
+
refreshToken: nextRefreshToken,
|
|
745
|
+
accessExpiresAt,
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function findLocalChromiumBrowser() {
|
|
750
|
+
const envCustom = typeof process.env.CODEX_CREDIT_BROWSER_PATH === 'string'
|
|
751
|
+
? process.env.CODEX_CREDIT_BROWSER_PATH.trim()
|
|
752
|
+
: ''
|
|
753
|
+
const candidates = []
|
|
754
|
+
if (envCustom) candidates.push({ name: 'Chromium', path: envCustom })
|
|
755
|
+
if (process.platform === 'darwin') {
|
|
756
|
+
candidates.push(
|
|
757
|
+
{ name: 'Google Chrome', path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' },
|
|
758
|
+
{ name: 'Google Chrome', path: join(homedir(), 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome') },
|
|
759
|
+
{ name: 'Microsoft Edge', path: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge' },
|
|
760
|
+
{ name: 'Microsoft Edge', path: join(homedir(), 'Applications', 'Microsoft Edge.app', 'Contents', 'MacOS', 'Microsoft Edge') },
|
|
761
|
+
{ name: 'Brave Browser', path: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser' },
|
|
762
|
+
{ name: 'Chromium', path: '/Applications/Chromium.app/Contents/MacOS/Chromium' },
|
|
763
|
+
{ name: 'Arc', path: '/Applications/Arc.app/Contents/MacOS/Arc' },
|
|
764
|
+
)
|
|
765
|
+
} else if (process.platform === 'win32') {
|
|
766
|
+
const pf = process.env.PROGRAMFILES || 'C:\\Program Files'
|
|
767
|
+
const pf86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)'
|
|
768
|
+
const localAppData = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local')
|
|
769
|
+
candidates.push(
|
|
770
|
+
{ name: 'Google Chrome', path: join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe') },
|
|
771
|
+
{ name: 'Google Chrome', path: join(pf86, 'Google', 'Chrome', 'Application', 'chrome.exe') },
|
|
772
|
+
{ name: 'Google Chrome', path: join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe') },
|
|
773
|
+
{ name: 'Microsoft Edge', path: join(pf86, 'Microsoft', 'Edge', 'Application', 'msedge.exe') },
|
|
774
|
+
{ name: 'Microsoft Edge', path: join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe') },
|
|
775
|
+
{ name: 'Brave Browser', path: join(pf, 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe') },
|
|
776
|
+
)
|
|
777
|
+
} else {
|
|
778
|
+
candidates.push(
|
|
779
|
+
{ name: 'Google Chrome', path: '/usr/bin/google-chrome' },
|
|
780
|
+
{ name: 'Google Chrome', path: '/usr/bin/google-chrome-stable' },
|
|
781
|
+
{ name: 'Chromium', path: '/usr/bin/chromium' },
|
|
782
|
+
{ name: 'Chromium', path: '/usr/bin/chromium-browser' },
|
|
783
|
+
{ name: 'Microsoft Edge', path: '/usr/bin/microsoft-edge' },
|
|
784
|
+
{ name: 'Brave Browser', path: '/usr/bin/brave-browser' },
|
|
785
|
+
)
|
|
786
|
+
}
|
|
787
|
+
return candidates.find(item => item.path && existsSync(item.path)) ?? null
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function getDedicatedBrowserProfileDir() {
|
|
791
|
+
const base = (typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME.trim())
|
|
792
|
+
? process.env.DSH_HOME.trim()
|
|
793
|
+
: join(homedir(), '.dsh')
|
|
794
|
+
return join(base, 'codex-credit-hub-browser')
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
export async function syncOpenAiSessionFromSystemBrowserOnce(signal, options = {}) {
|
|
798
|
+
const browser = findLocalChromiumBrowser()
|
|
799
|
+
if (!browser) {
|
|
800
|
+
return {
|
|
801
|
+
code: 'no-browser',
|
|
802
|
+
error: '未检测到 Ego Lite 或 Chrome / Edge 等本地浏览器,请安装 Chrome / Edge 或 Ego Lite 后重试',
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
if (typeof WebSocket !== 'function') {
|
|
806
|
+
return {
|
|
807
|
+
code: 'no-websocket',
|
|
808
|
+
error: '当前运行环境不支持本地浏览器 DevTools 连接,请使用 Ego Lite 重试',
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const profileDir = getDedicatedBrowserProfileDir()
|
|
813
|
+
await mkdir(profileDir, { recursive: true, mode: 0o700 })
|
|
814
|
+
const portPath = join(profileDir, 'DevToolsActivePort')
|
|
815
|
+
let existingPort = ''
|
|
816
|
+
try {
|
|
817
|
+
const [port] = (await readFile(portPath, 'utf8')).trim().split('\n')
|
|
818
|
+
if (/^\d+$/.test(port || '')) {
|
|
819
|
+
const alive = await fetch(`http://127.0.0.1:${port}/json/version`, {
|
|
820
|
+
signal: AbortSignal.timeout(1200),
|
|
821
|
+
}).then(r => r.ok).catch(() => false)
|
|
822
|
+
if (alive) existingPort = port
|
|
823
|
+
}
|
|
824
|
+
} catch {}
|
|
825
|
+
if (!existingPort) await rm(portPath, { force: true }).catch(() => {})
|
|
826
|
+
|
|
827
|
+
return await new Promise((resolve) => {
|
|
828
|
+
let settled = false
|
|
829
|
+
let ws = null
|
|
830
|
+
let pollTimer = null
|
|
831
|
+
let timeoutTimer = null
|
|
832
|
+
let child = null
|
|
833
|
+
let launched = false
|
|
834
|
+
|
|
835
|
+
const closeAttachedBrowser = async (port) => {
|
|
836
|
+
if (!port) return
|
|
837
|
+
try {
|
|
838
|
+
const version = await fetch(`http://127.0.0.1:${port}/json/version`, {
|
|
839
|
+
signal: AbortSignal.timeout(1500),
|
|
840
|
+
}).then(r => r.json())
|
|
841
|
+
const browserWs = version?.webSocketDebuggerUrl
|
|
842
|
+
if (!browserWs) return
|
|
843
|
+
const socket = new WebSocket(browserWs)
|
|
844
|
+
await new Promise((resolveClose) => {
|
|
845
|
+
const timer = setTimeout(resolveClose, 1200)
|
|
846
|
+
socket.onopen = () => {
|
|
847
|
+
socket.send(JSON.stringify({ id: 1, method: 'Browser.close' }))
|
|
848
|
+
clearTimeout(timer)
|
|
849
|
+
resolveClose()
|
|
850
|
+
}
|
|
851
|
+
socket.onerror = () => { clearTimeout(timer); resolveClose() }
|
|
852
|
+
})
|
|
853
|
+
try { socket.close() } catch {}
|
|
854
|
+
} catch {}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const cleanup = async (value) => {
|
|
858
|
+
if (pollTimer) { clearTimeout(pollTimer); pollTimer = null }
|
|
859
|
+
if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
|
|
860
|
+
signal?.removeEventListener('abort', onAbort)
|
|
861
|
+
if (ws) { try { ws.close() } catch {} ws = null }
|
|
862
|
+
if (launched && child) {
|
|
863
|
+
if (child.exitCode !== null || child.signalCode) return
|
|
864
|
+
await new Promise((resolveExit) => {
|
|
865
|
+
let done = false
|
|
866
|
+
const finishExit = () => {
|
|
867
|
+
if (done) return
|
|
868
|
+
done = true
|
|
869
|
+
clearTimeout(forceTimer)
|
|
870
|
+
resolveExit()
|
|
871
|
+
}
|
|
872
|
+
const forceTimer = setTimeout(() => {
|
|
873
|
+
try { child.kill('SIGKILL') } catch {}
|
|
874
|
+
finishExit()
|
|
875
|
+
}, 900)
|
|
876
|
+
forceTimer.unref?.()
|
|
877
|
+
child.once('exit', finishExit)
|
|
878
|
+
try { child.kill('SIGTERM') } catch { finishExit() }
|
|
879
|
+
})
|
|
880
|
+
} else if (value?.ok && existingPort) {
|
|
881
|
+
await closeAttachedBrowser(existingPort)
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
const finish = (value) => {
|
|
885
|
+
if (settled) return
|
|
886
|
+
settled = true
|
|
887
|
+
void cleanup(value).finally(() => resolve(value))
|
|
888
|
+
}
|
|
889
|
+
const onAbort = () => finish({ code: 'aborted', error: 'OpenAI 浏览器登录已取消' })
|
|
890
|
+
if (signal?.aborted) {
|
|
891
|
+
onAbort()
|
|
892
|
+
return
|
|
893
|
+
}
|
|
894
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
895
|
+
|
|
896
|
+
const timeoutMs = options.timeoutMs ?? 180_000
|
|
897
|
+
timeoutTimer = setTimeout(() => {
|
|
898
|
+
finish({ code: 'login-timeout', error: `等待 ${browser.name} 登录 OpenAI Platform 超时(${Math.round(timeoutMs / 1000)} 秒),请重试` })
|
|
899
|
+
}, timeoutMs)
|
|
900
|
+
timeoutTimer.unref?.()
|
|
901
|
+
|
|
902
|
+
if (!existingPort) {
|
|
903
|
+
const args = [
|
|
904
|
+
`--user-data-dir=${profileDir}`,
|
|
905
|
+
'--remote-debugging-port=0',
|
|
906
|
+
'--no-first-run',
|
|
907
|
+
'--no-default-browser-check',
|
|
908
|
+
'--new-window',
|
|
909
|
+
]
|
|
910
|
+
if (options.headless) args.push('--headless=new')
|
|
911
|
+
args.push(OPENAI_PLATFORM_HOME_URL)
|
|
912
|
+
launched = true
|
|
913
|
+
child = spawn(browser.path, args, { stdio: 'ignore', windowsHide: false })
|
|
914
|
+
child.on('error', (error) => {
|
|
915
|
+
finish({ code: 'browser-launch-failed', error: scrubSecrets(`无法启动 ${browser.name}: ${error.message}`) })
|
|
916
|
+
})
|
|
917
|
+
child.on('exit', () => {
|
|
918
|
+
if (!settled) finish({ code: 'login-cancelled', error: `${browser.name} 登录窗口已关闭,尚未完成 OpenAI Platform 登录` })
|
|
919
|
+
})
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const evalPage = (targetWsUrl, expression) => new Promise((resolveEval, rejectEval) => {
|
|
923
|
+
const targetWs = new WebSocket(targetWsUrl)
|
|
924
|
+
ws = targetWs
|
|
925
|
+
let done = false
|
|
926
|
+
const finishEval = (fn, value) => {
|
|
927
|
+
if (done) return
|
|
928
|
+
done = true
|
|
929
|
+
clearTimeout(reqTimer)
|
|
930
|
+
try { targetWs.close() } catch {}
|
|
931
|
+
if (ws === targetWs) ws = null
|
|
932
|
+
fn(value)
|
|
933
|
+
}
|
|
934
|
+
const reqTimer = setTimeout(() => finishEval(rejectEval, new Error('CDP evaluate timeout')), 25_000)
|
|
935
|
+
reqTimer.unref?.()
|
|
936
|
+
targetWs.onopen = () => {
|
|
937
|
+
targetWs.send(JSON.stringify({
|
|
938
|
+
id: 1,
|
|
939
|
+
method: 'Runtime.evaluate',
|
|
940
|
+
params: { expression, awaitPromise: true, returnByValue: true },
|
|
941
|
+
}))
|
|
942
|
+
}
|
|
943
|
+
targetWs.onmessage = (event) => {
|
|
944
|
+
try {
|
|
945
|
+
const msg = JSON.parse(String(event.data))
|
|
946
|
+
if (msg.id !== 1) return
|
|
947
|
+
if (msg.error) finishEval(rejectEval, new Error(msg.error.message || 'CDP error'))
|
|
948
|
+
else finishEval(resolveEval, msg.result?.result?.value)
|
|
949
|
+
} catch {}
|
|
950
|
+
}
|
|
951
|
+
targetWs.onerror = () => finishEval(rejectEval, new Error('CDP websocket error'))
|
|
952
|
+
targetWs.onclose = () => {
|
|
953
|
+
if (!done) finishEval(rejectEval, new Error('CDP websocket closed'))
|
|
954
|
+
}
|
|
955
|
+
})
|
|
956
|
+
|
|
957
|
+
const pollOnce = async () => {
|
|
958
|
+
if (settled) return
|
|
959
|
+
try {
|
|
960
|
+
const port = existingPort || (await readFile(portPath, 'utf8').catch(() => '')).trim().split('\n')[0]
|
|
961
|
+
if (port && /^\d+$/.test(port)) {
|
|
962
|
+
const targets = await fetch(`http://127.0.0.1:${port}/json/list`, {
|
|
963
|
+
signal: AbortSignal.timeout(2000),
|
|
964
|
+
}).then(r => r.json()).catch(() => [])
|
|
965
|
+
const pageTarget = Array.isArray(targets)
|
|
966
|
+
? targets.find(t => t.type === 'page' && typeof t.url === 'string' && t.url.startsWith('https://platform.openai.com'))
|
|
967
|
+
: null
|
|
968
|
+
if (pageTarget?.webSocketDebuggerUrl) {
|
|
969
|
+
const payload = await evalPage(pageTarget.webSocketDebuggerUrl, `(async () => {
|
|
970
|
+
const raw = localStorage.getItem(${JSON.stringify(OPENAI_PLATFORM_AUTH_KEY)});
|
|
971
|
+
const auth = raw ? JSON.parse(raw) : null;
|
|
972
|
+
const accessToken = typeof auth?.accessToken === "string" ? auth.accessToken : "";
|
|
973
|
+
const refreshToken = typeof auth?.refreshToken === "string" ? auth.refreshToken : "";
|
|
974
|
+
if (!accessToken) return null;
|
|
975
|
+
let accessExpiresAt = 0;
|
|
976
|
+
try {
|
|
977
|
+
const parts = accessToken.split(".");
|
|
978
|
+
if (parts[1]) {
|
|
979
|
+
const p = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
980
|
+
if (typeof p?.exp === "number") accessExpiresAt = p.exp > 1e12 ? p.exp : p.exp * 1000;
|
|
981
|
+
}
|
|
982
|
+
} catch {}
|
|
983
|
+
const readJson = async r => { const t = await r.text(); try { return JSON.parse(t); } catch { return null; } };
|
|
984
|
+
const login = await fetch(${JSON.stringify(OPENAI_ONBOARDING_LOGIN_URL)}, {
|
|
985
|
+
method: "POST",
|
|
986
|
+
headers: { Authorization: "Bearer " + accessToken, "Content-Type": "application/json" },
|
|
987
|
+
body: "{}",
|
|
988
|
+
});
|
|
989
|
+
const loginBody = await readJson(login);
|
|
990
|
+
if (login.status === 401 || login.status === 403) return { authExpired: true };
|
|
991
|
+
if (!login.ok || !loginBody) return { retry: true };
|
|
992
|
+
const sessionKey = loginBody?.user?.session?.sensitive_id;
|
|
993
|
+
if (typeof sessionKey !== "string" || !sessionKey.startsWith("sess-")) return { retry: true };
|
|
994
|
+
const orgs = Array.isArray(loginBody?.user?.orgs?.data) ? loginBody.user.orgs.data : [];
|
|
995
|
+
const org = orgs.find(x => x.personal) || orgs[0];
|
|
996
|
+
const organizationId = typeof org?.id === "string" ? org.id : "";
|
|
997
|
+
const billing = await fetch(${JSON.stringify(OPENAI_CREDIT_GRANTS_URL)}, {
|
|
998
|
+
method: "GET",
|
|
999
|
+
headers: {
|
|
1000
|
+
Authorization: "Bearer " + sessionKey,
|
|
1001
|
+
Accept: "application/json",
|
|
1002
|
+
...(organizationId ? { "OpenAI-Organization": organizationId } : {}),
|
|
1003
|
+
},
|
|
1004
|
+
});
|
|
1005
|
+
const billingBody = await readJson(billing);
|
|
1006
|
+
if (!billing.ok || !billingBody || billingBody.total_granted === undefined || billingBody.total_used === undefined) {
|
|
1007
|
+
return { retry: true };
|
|
1008
|
+
}
|
|
1009
|
+
return { ok: true, sessionKey, organizationId, accessToken, refreshToken, accessExpiresAt, balance: billingBody };
|
|
1010
|
+
})()`)
|
|
1011
|
+
if (payload?.ok && payload.sessionKey) {
|
|
1012
|
+
finish(payload)
|
|
1013
|
+
return
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
} catch {}
|
|
1018
|
+
if (!settled) {
|
|
1019
|
+
pollTimer = setTimeout(() => { void pollOnce() }, 1000)
|
|
1020
|
+
pollTimer.unref?.()
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
pollTimer = setTimeout(() => { void pollOnce() }, options.headless ? 100 : 800)
|
|
1025
|
+
pollTimer.unref?.()
|
|
1026
|
+
})
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
async function syncOpenAiSessionFromBrowser(force = false, signal, options = {}) {
|
|
1030
|
+
const allowSystemBrowser = options.allowSystemBrowser !== false
|
|
657
1031
|
if (openAiBrowserSyncInFlight) return await subscribeOpenAiBrowserSync(openAiBrowserSyncInFlight, signal)
|
|
658
|
-
if (!force &&
|
|
659
|
-
return {
|
|
1032
|
+
if (!force && openAiLoginPending) {
|
|
1033
|
+
return {
|
|
1034
|
+
code: 'login-required',
|
|
1035
|
+
needsLogin: true,
|
|
1036
|
+
taskSpaceId: openAiLoginPending.taskSpaceId,
|
|
1037
|
+
error: 'OpenAI 登录页已打开,请先完成登录,再点击「同步 OpenAI 登录态」;后台不会打断登录',
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
const cooldownMs = openAiBrowserSyncLastErrorCode === 'login-required'
|
|
1041
|
+
? OPENAI_BROWSER_SYNC_COOLDOWN_MS
|
|
1042
|
+
: 10_000
|
|
1043
|
+
if (!force && openAiBrowserSyncLastAttempt > 0 && openAiBrowserSyncLastError && Date.now() - openAiBrowserSyncLastAttempt < cooldownMs) {
|
|
1044
|
+
return { code: openAiBrowserSyncLastErrorCode, error: openAiBrowserSyncLastError }
|
|
660
1045
|
}
|
|
661
1046
|
openAiBrowserSyncLastAttempt = Date.now()
|
|
662
1047
|
openAiBrowserSyncLastError = ''
|
|
1048
|
+
openAiBrowserSyncLastErrorCode = ''
|
|
663
1049
|
const entry = {
|
|
664
1050
|
controller: new AbortController(),
|
|
665
1051
|
subscribers: new Set(),
|
|
666
1052
|
abortTimer: null,
|
|
667
1053
|
promise: null,
|
|
668
1054
|
}
|
|
669
|
-
entry.promise =
|
|
1055
|
+
entry.promise = (async () => {
|
|
1056
|
+
const egoResult = await syncOpenAiSessionFromEgoBrowserOnce(entry.controller.signal, false)
|
|
1057
|
+
if (egoResult?.sessionKey) return egoResult
|
|
1058
|
+
if (!allowSystemBrowser) {
|
|
1059
|
+
if (egoResult?.code === 'no-ego-browser' || egoResult?.code === 'login-required') {
|
|
1060
|
+
return {
|
|
1061
|
+
code: 'login-required',
|
|
1062
|
+
error: 'OpenAI Platform 登录态已过期,请点击「同步 OpenAI 登录态」重新登录',
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
return egoResult
|
|
1066
|
+
}
|
|
1067
|
+
const systemResult = await syncOpenAiSessionFromSystemBrowserOnce(entry.controller.signal)
|
|
1068
|
+
// If no Chromium browser exists but Ego Lite is present, use its login
|
|
1069
|
+
// page as the final fallback instead of leaving the user without a path.
|
|
1070
|
+
if (systemResult?.code === 'no-browser' && egoResult?.code === 'login-required') {
|
|
1071
|
+
return await syncOpenAiSessionFromEgoBrowserOnce(entry.controller.signal, true)
|
|
1072
|
+
}
|
|
1073
|
+
return systemResult
|
|
1074
|
+
})()
|
|
670
1075
|
.then(result => {
|
|
671
|
-
|
|
1076
|
+
openAiBrowserSyncLastError = result?.error ? scrubSecrets(result.error) : ''
|
|
1077
|
+
openAiBrowserSyncLastErrorCode = result?.error ? (result?.code || 'sync-failed') : ''
|
|
1078
|
+
openAiLoginPending = result?.needsLogin && result?.taskSpaceId
|
|
1079
|
+
? { taskSpaceId: result.taskSpaceId }
|
|
1080
|
+
: null
|
|
1081
|
+
return result
|
|
1082
|
+
})
|
|
1083
|
+
.catch(() => {
|
|
1084
|
+
const result = { code: 'sync-failed', error: 'OpenAI 浏览器同步失败,请稍后重试' }
|
|
1085
|
+
openAiBrowserSyncLastError = result.error
|
|
1086
|
+
openAiBrowserSyncLastErrorCode = result.code
|
|
672
1087
|
return result
|
|
673
1088
|
})
|
|
674
|
-
.catch(() => ({ error: 'OpenAI 浏览器同步失败,请稍后重试' }))
|
|
675
1089
|
.finally(() => {
|
|
676
1090
|
if (entry.abortTimer) {
|
|
677
1091
|
clearTimeout(entry.abortTimer)
|
|
@@ -807,6 +1221,8 @@ export class CodexApiQuotaService {
|
|
|
807
1221
|
this.generation = 0
|
|
808
1222
|
this.disposed = false
|
|
809
1223
|
this.controllers = new Set()
|
|
1224
|
+
this.failureCount = 0
|
|
1225
|
+
this.oauthInFlight = null
|
|
810
1226
|
}
|
|
811
1227
|
|
|
812
1228
|
dispose() {
|
|
@@ -826,25 +1242,81 @@ export class CodexApiQuotaService {
|
|
|
826
1242
|
}
|
|
827
1243
|
|
|
828
1244
|
commit(generation, state) {
|
|
1245
|
+
if (state?.status === 'ok' && !state.error) this.failureCount = 0
|
|
829
1246
|
if (generation === this.generation) this.cached = state
|
|
830
1247
|
return this.cached ?? state
|
|
831
1248
|
}
|
|
832
1249
|
|
|
1250
|
+
commitFailure(generation, failure) {
|
|
1251
|
+
this.failureCount += 1
|
|
1252
|
+
const retryAfterSec = failure.code === 'login-required'
|
|
1253
|
+
? 60
|
|
1254
|
+
: Math.min(60, 15 * (2 ** Math.min(this.failureCount - 1, 2)))
|
|
1255
|
+
if (this.cached?.quota) {
|
|
1256
|
+
return this.commit(generation, {
|
|
1257
|
+
...this.cached,
|
|
1258
|
+
status: 'ok',
|
|
1259
|
+
stale: true,
|
|
1260
|
+
error: failure.error,
|
|
1261
|
+
retryAfterSec,
|
|
1262
|
+
canSync: true,
|
|
1263
|
+
preferences: this.getPreferences(),
|
|
1264
|
+
})
|
|
1265
|
+
}
|
|
1266
|
+
return this.commit(generation, {
|
|
1267
|
+
status: failure.status || 'error',
|
|
1268
|
+
error: failure.error,
|
|
1269
|
+
retryAfterSec,
|
|
1270
|
+
canSync: true,
|
|
1271
|
+
webUrl: OPENAI_API_WEB_URL,
|
|
1272
|
+
preferences: this.getPreferences(),
|
|
1273
|
+
})
|
|
1274
|
+
}
|
|
1275
|
+
|
|
833
1276
|
async readStoredSession() {
|
|
834
1277
|
try {
|
|
835
1278
|
const record = await this.ctx.credentials.readRecord(this.key)
|
|
836
1279
|
if (record?.kind !== 'grant' || !record.payload || typeof record.payload !== 'object') return null
|
|
837
1280
|
const sessionKey = normalizeSecretInput(record.payload.sessionKey)
|
|
838
|
-
|
|
1281
|
+
const accessToken = normalizeSecretInput(record.payload.accessToken)
|
|
1282
|
+
const refreshToken = normalizeSecretInput(record.payload.refreshToken)
|
|
1283
|
+
if (!sessionKey && !accessToken && !refreshToken) return null
|
|
1284
|
+
const expires = Number(record.payload.accessExpiresAt)
|
|
839
1285
|
return {
|
|
840
1286
|
sessionKey,
|
|
841
1287
|
organizationId: typeof record.payload.organizationId === 'string' ? record.payload.organizationId.trim() : '',
|
|
1288
|
+
accessToken,
|
|
1289
|
+
refreshToken,
|
|
1290
|
+
accessExpiresAt: Number.isFinite(expires) ? expires : 0,
|
|
842
1291
|
}
|
|
843
1292
|
} catch {
|
|
844
1293
|
return null
|
|
845
1294
|
}
|
|
846
1295
|
}
|
|
847
1296
|
|
|
1297
|
+
async saveCredentials(patch, expectedRefreshToken = '') {
|
|
1298
|
+
if (this.disposed) throw new Error('Codex API 服务已卸载')
|
|
1299
|
+
let applied = true
|
|
1300
|
+
await this.ctx.credentials.modifyRecord(this.key, async current => {
|
|
1301
|
+
if (this.disposed) {
|
|
1302
|
+
applied = false
|
|
1303
|
+
return current
|
|
1304
|
+
}
|
|
1305
|
+
if (expectedRefreshToken && current?.payload?.refreshToken !== expectedRefreshToken) {
|
|
1306
|
+
applied = false
|
|
1307
|
+
return current
|
|
1308
|
+
}
|
|
1309
|
+
const previous = current?.kind === 'grant' && current.payload && typeof current.payload === 'object'
|
|
1310
|
+
? current.payload
|
|
1311
|
+
: {}
|
|
1312
|
+
return {
|
|
1313
|
+
kind: 'grant',
|
|
1314
|
+
payload: { ...previous, ...patch },
|
|
1315
|
+
}
|
|
1316
|
+
})
|
|
1317
|
+
return applied
|
|
1318
|
+
}
|
|
1319
|
+
|
|
848
1320
|
async getQuota(options = {}) {
|
|
849
1321
|
const { force = false, signal } = options
|
|
850
1322
|
if (!force && this.cached && this.cached.status === 'ok') {
|
|
@@ -889,38 +1361,140 @@ export class CodexApiQuotaService {
|
|
|
889
1361
|
|
|
890
1362
|
async _resolveQuota(signal, generation) {
|
|
891
1363
|
const stored = await this.readStoredSession()
|
|
892
|
-
if (stored) {
|
|
1364
|
+
if (!stored) {
|
|
1365
|
+
return this.commit(generation, {
|
|
1366
|
+
status: 'unauthorized',
|
|
1367
|
+
error: '尚未连接 OpenAI Platform。点击「同步 OpenAI 登录态」开始连接;无需输入 API Key',
|
|
1368
|
+
canSync: true,
|
|
1369
|
+
webUrl: OPENAI_API_WEB_URL,
|
|
1370
|
+
preferences: this.getPreferences(),
|
|
1371
|
+
})
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
if (stored.sessionKey.startsWith('sess-')) {
|
|
893
1375
|
const result = await fetchOpenAiCreditBalance(stored.sessionKey, stored.organizationId, signal)
|
|
894
1376
|
if (result.ok) {
|
|
895
1377
|
return this.commit(generation, {
|
|
896
1378
|
status: 'ok',
|
|
897
|
-
source: 'openai-platform-
|
|
1379
|
+
source: 'openai-platform-session',
|
|
898
1380
|
quota: result.data,
|
|
899
1381
|
preferences: this.getPreferences(),
|
|
900
1382
|
})
|
|
901
1383
|
}
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
1384
|
+
if (result.status !== 401 && result.status !== 403 && !result.network) {
|
|
1385
|
+
return this.commitFailure(generation, { status: 'error', error: result.message })
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
if (stored.accessToken || stored.refreshToken) {
|
|
1390
|
+
const oauth = await this._resolveViaOAuth(stored, signal)
|
|
1391
|
+
if (oauth.ok) {
|
|
905
1392
|
return this.commit(generation, {
|
|
906
|
-
status: '
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
webUrl: OPENAI_API_WEB_URL,
|
|
1393
|
+
status: 'ok',
|
|
1394
|
+
source: 'openai-platform-oauth',
|
|
1395
|
+
quota: oauth.data,
|
|
910
1396
|
preferences: this.getPreferences(),
|
|
911
1397
|
})
|
|
912
1398
|
}
|
|
1399
|
+
if (oauth.code !== 'login-required' && oauth.code !== 'no-oauth') {
|
|
1400
|
+
return this.commitFailure(generation, { status: 'error', code: oauth.code, error: oauth.message })
|
|
1401
|
+
}
|
|
913
1402
|
}
|
|
914
1403
|
|
|
915
|
-
|
|
1404
|
+
// Background recovery may reuse an already logged-in Ego Lite profile, but
|
|
1405
|
+
// never opens a new system browser window without an explicit user action.
|
|
1406
|
+
const synced = await this.syncFromBrowser({
|
|
1407
|
+
internal: true,
|
|
1408
|
+
allowSystemBrowser: false,
|
|
1409
|
+
signal,
|
|
1410
|
+
expectedGeneration: generation,
|
|
1411
|
+
})
|
|
916
1412
|
if (synced.ok) return synced.state
|
|
917
|
-
return this.
|
|
918
|
-
status: 'unauthorized',
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
1413
|
+
return this.commitFailure(generation, {
|
|
1414
|
+
status: synced.code === 'login-required' ? 'unauthorized' : 'error',
|
|
1415
|
+
code: synced.code,
|
|
1416
|
+
error: synced.error || 'OpenAI Platform 登录态已过期,请点击「同步 OpenAI 登录态」重新登录',
|
|
1417
|
+
})
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
async _resolveViaOAuth(stored, signal) {
|
|
1421
|
+
if (this.oauthInFlight) return await this._waitForOAuth(this.oauthInFlight.promise, signal)
|
|
1422
|
+
const controller = new AbortController()
|
|
1423
|
+
this.controllers.add(controller)
|
|
1424
|
+
const entry = { controller, promise: null }
|
|
1425
|
+
entry.promise = this._resolveViaOAuthOnce(stored, controller.signal).finally(() => {
|
|
1426
|
+
this.controllers.delete(controller)
|
|
1427
|
+
if (this.oauthInFlight === entry) this.oauthInFlight = null
|
|
923
1428
|
})
|
|
1429
|
+
this.oauthInFlight = entry
|
|
1430
|
+
return await this._waitForOAuth(entry.promise, signal)
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
async _waitForOAuth(promise, signal) {
|
|
1434
|
+
if (!signal) return await promise
|
|
1435
|
+
if (signal.aborted) return { ok: false, code: 'aborted', message: 'OpenAI OAuth 请求已取消' }
|
|
1436
|
+
let onAbort
|
|
1437
|
+
const cancelled = new Promise(resolve => {
|
|
1438
|
+
onAbort = () => resolve({ ok: false, code: 'aborted', message: 'OpenAI OAuth 请求已取消' })
|
|
1439
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
1440
|
+
})
|
|
1441
|
+
try {
|
|
1442
|
+
return await Promise.race([promise, cancelled])
|
|
1443
|
+
} finally {
|
|
1444
|
+
signal.removeEventListener('abort', onAbort)
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
async _resolveViaOAuthOnce(stored, signal) {
|
|
1449
|
+
let accessToken = stored.accessToken
|
|
1450
|
+
let refreshToken = stored.refreshToken
|
|
1451
|
+
let accessExpiresAt = stored.accessExpiresAt
|
|
1452
|
+
let didRefresh = false
|
|
1453
|
+
|
|
1454
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1455
|
+
if (!isTokenUsable(accessToken, accessExpiresAt)) {
|
|
1456
|
+
if (!refreshToken) return { ok: false, code: 'no-oauth', message: '缺少可用的 OpenAI Platform OAuth 令牌' }
|
|
1457
|
+
const refreshed = await refreshOpenAiPlatformOAuthToken(refreshToken, '', signal)
|
|
1458
|
+
if (!refreshed.ok) return refreshed
|
|
1459
|
+
accessToken = refreshed.accessToken
|
|
1460
|
+
refreshToken = refreshed.refreshToken
|
|
1461
|
+
accessExpiresAt = refreshed.accessExpiresAt
|
|
1462
|
+
didRefresh = true
|
|
1463
|
+
try {
|
|
1464
|
+
// Persist a rotated refresh token before any subsequent network call.
|
|
1465
|
+
const applied = await this.saveCredentials({ accessToken, refreshToken, accessExpiresAt }, stored.refreshToken)
|
|
1466
|
+
if (!applied) return { ok: false, code: 'credential-changed', message: 'OpenAI 凭证已被其他同步更新,请重试' }
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
return { ok: false, code: 'credential-write-failed', message: scrubSecrets(error instanceof Error ? error.message : String(error)) }
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
const exchanged = await exchangeOpenAiAccessTokenForSession(accessToken, signal)
|
|
1473
|
+
if (!exchanged.ok) {
|
|
1474
|
+
if (exchanged.code === 'login-required' && refreshToken && !didRefresh) {
|
|
1475
|
+
accessToken = ''
|
|
1476
|
+
accessExpiresAt = 0
|
|
1477
|
+
continue
|
|
1478
|
+
}
|
|
1479
|
+
return exchanged
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
const balance = await fetchOpenAiCreditBalance(exchanged.sessionKey, exchanged.organizationId, signal)
|
|
1483
|
+
if (!balance.ok) return balance
|
|
1484
|
+
try {
|
|
1485
|
+
await this.saveCredentials({
|
|
1486
|
+
sessionKey: exchanged.sessionKey,
|
|
1487
|
+
organizationId: exchanged.organizationId,
|
|
1488
|
+
accessToken,
|
|
1489
|
+
refreshToken,
|
|
1490
|
+
accessExpiresAt,
|
|
1491
|
+
})
|
|
1492
|
+
} catch (error) {
|
|
1493
|
+
return { ok: false, code: 'credential-write-failed', message: scrubSecrets(error instanceof Error ? error.message : String(error)) }
|
|
1494
|
+
}
|
|
1495
|
+
return { ok: true, data: balance.data }
|
|
1496
|
+
}
|
|
1497
|
+
return { ok: false, code: 'login-required', message: 'OpenAI Platform OAuth 令牌已失效,请重新同步' }
|
|
924
1498
|
}
|
|
925
1499
|
|
|
926
1500
|
async syncFromBrowser(options = {}) {
|
|
@@ -928,12 +1502,14 @@ export class CodexApiQuotaService {
|
|
|
928
1502
|
if (generation !== this.generation || this.disposed) {
|
|
929
1503
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
930
1504
|
}
|
|
931
|
-
const synced = await
|
|
1505
|
+
const synced = await syncOpenAiSessionFromBrowser(Boolean(options.force), options.signal, {
|
|
1506
|
+
allowSystemBrowser: options.allowSystemBrowser !== false,
|
|
1507
|
+
})
|
|
932
1508
|
if (generation !== this.generation || this.disposed) {
|
|
933
1509
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
934
1510
|
}
|
|
935
1511
|
if (!synced?.sessionKey) {
|
|
936
|
-
return { ok: false, error: scrubSecrets(synced?.error || '未能同步 OpenAI Platform 登录态') }
|
|
1512
|
+
return { ok: false, code: synced?.code || '', error: scrubSecrets(synced?.error || '未能同步 OpenAI Platform 登录态') }
|
|
937
1513
|
}
|
|
938
1514
|
return await this.saveSession(synced, { ...options, expectedGeneration: generation })
|
|
939
1515
|
}
|
|
@@ -943,7 +1519,10 @@ export class CodexApiQuotaService {
|
|
|
943
1519
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
944
1520
|
}
|
|
945
1521
|
const generation = ++this.generation
|
|
946
|
-
if (!options.internal)
|
|
1522
|
+
if (!options.internal) {
|
|
1523
|
+
this.inFlight?.abort()
|
|
1524
|
+
openAiLoginPending = null
|
|
1525
|
+
}
|
|
947
1526
|
const sessionKey = normalizeSecretInput(session.sessionKey)
|
|
948
1527
|
const organizationId = typeof session.organizationId === 'string' ? session.organizationId.trim() : ''
|
|
949
1528
|
if (!sessionKey.startsWith('sess-')) return { ok: false, error: 'OpenAI Platform 登录态无效,请重新同步' }
|
|
@@ -954,22 +1533,29 @@ export class CodexApiQuotaService {
|
|
|
954
1533
|
options.signal?.addEventListener('abort', onAbort, { once: true })
|
|
955
1534
|
let probe
|
|
956
1535
|
try {
|
|
957
|
-
|
|
1536
|
+
if (session.balance && typeof session.balance === 'object') {
|
|
1537
|
+
probe = await fetchOpenAiCreditBalanceFromBody(session.balance, organizationId)
|
|
1538
|
+
} else {
|
|
1539
|
+
probe = await fetchOpenAiCreditBalance(sessionKey, organizationId, controller.signal)
|
|
1540
|
+
}
|
|
1541
|
+
} catch (error) {
|
|
1542
|
+
probe = { ok: false, error: scrubSecrets(error instanceof Error ? error.message : String(error)) }
|
|
958
1543
|
} finally {
|
|
959
1544
|
options.signal?.removeEventListener('abort', onAbort)
|
|
960
1545
|
this.controllers.delete(controller)
|
|
961
1546
|
}
|
|
962
1547
|
if (generation !== this.generation || this.disposed) return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
963
|
-
if (!probe.ok) return { ok: false, error: probe.message }
|
|
1548
|
+
if (!probe.ok) return { ok: false, error: probe.message || probe.error || 'OpenAI 余额校验失败,请重试' }
|
|
964
1549
|
|
|
965
1550
|
const payload = {
|
|
966
1551
|
sessionKey,
|
|
967
1552
|
organizationId,
|
|
968
|
-
source: 'openai-platform-browser',
|
|
969
|
-
updatedAt: Date.now(),
|
|
970
1553
|
}
|
|
1554
|
+
if (session.accessToken) payload.accessToken = session.accessToken
|
|
1555
|
+
if (session.refreshToken) payload.refreshToken = session.refreshToken
|
|
1556
|
+
if (session.accessExpiresAt) payload.accessExpiresAt = session.accessExpiresAt
|
|
971
1557
|
try {
|
|
972
|
-
await this.
|
|
1558
|
+
await this.saveCredentials(payload)
|
|
973
1559
|
} catch (error) {
|
|
974
1560
|
return { ok: false, error: '会话已验证,但保存到 DSH 凭证库失败: ' + scrubSecrets(error instanceof Error ? error.message : String(error)) }
|
|
975
1561
|
}
|
|
@@ -977,7 +1563,7 @@ export class CodexApiQuotaService {
|
|
|
977
1563
|
|
|
978
1564
|
const state = {
|
|
979
1565
|
status: 'ok',
|
|
980
|
-
source: 'openai-platform-browser',
|
|
1566
|
+
source: session.source || 'openai-platform-browser',
|
|
981
1567
|
quota: probe.data,
|
|
982
1568
|
preferences: this.getPreferences(),
|
|
983
1569
|
}
|
package/locale/en.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Codex Credit Hub",
|
|
4
|
-
"description": "Displays live Codex subscription rate limits and OpenAI / Codex API credit balances above the account avatar.
|
|
4
|
+
"description": "Displays live Codex subscription rate limits and OpenAI / Codex API credit balances above the account avatar. Reuses Ego Lite when available, or opens a dedicated system Chrome / Edge login window once; subsequent OAuth refreshes run in the background. No API key input or storage. Includes Refresh and Sync OpenAI login actions plus codex_cli_quota and codex_api_quota agent tools.",
|
|
5
5
|
"detail": "docs/DETAIL.md"
|
|
6
6
|
}
|
|
7
7
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Codex 额度监控",
|
|
4
|
-
"description": "在左侧边栏底部、头像上方显示「Codex」订阅限流窗口和「Codex API」OpenAI
|
|
4
|
+
"description": "在左侧边栏底部、头像上方显示「Codex」订阅限流窗口和「Codex API」OpenAI 平台真实余额。优先复用 Ego Lite,没有时可用系统 Chrome / Edge 完成一次登录;后续 OAuth 续期在后台自动完成,无需输入 API Key。支持「刷新」与「同步 OpenAI 登录态」,并提供 codex_cli_quota 与 codex_api_quota 两个 Agent 工具。",
|
|
5
5
|
"detail": "docs/DETAIL.zh.md"
|
|
6
6
|
}
|
|
7
7
|
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
const ALLOW_HANDOFF = __ALLOW_HANDOFF__;
|
|
2
|
+
const spaces = await listTaskSpaces();
|
|
3
|
+
const existing = spaces.find(space => space.name === "codex-credit-openai-session");
|
|
4
|
+
let task;
|
|
5
|
+
if (existing?.ownership === "agentDelegatedToUser") {
|
|
6
|
+
task = await takeOverTaskSpace(existing.id);
|
|
7
|
+
} else if (existing?.ownership === "user") {
|
|
8
|
+
task = await claimTaskSpace(existing.id);
|
|
9
|
+
} else if (existing) {
|
|
10
|
+
task = await taskSpace(existing.id);
|
|
11
|
+
} else {
|
|
12
|
+
task = await taskSpace("codex-credit-openai-session");
|
|
13
|
+
}
|
|
14
|
+
const pages = await task.pages();
|
|
15
|
+
const page = pages[0] ?? await task.adopt((await task.tabs())[0].page);
|
|
16
|
+
let result = { sessionKey: null, organizationId: "", balance: null, error: "", code: "" };
|
|
17
|
+
|
|
18
|
+
const readBalance = async () => {
|
|
19
|
+
return await page.evaluate(async () => {
|
|
20
|
+
const request = async (url, options) => {
|
|
21
|
+
const controller = new AbortController();
|
|
22
|
+
const timer = setTimeout(() => controller.abort(), 20000);
|
|
23
|
+
try {
|
|
24
|
+
return await fetch(url, { ...options, signal: controller.signal });
|
|
25
|
+
} finally {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const readJson = async response => {
|
|
30
|
+
const text = await response.text();
|
|
31
|
+
try { return { response, body: JSON.parse(text) }; }
|
|
32
|
+
catch { return { response, body: null }; }
|
|
33
|
+
};
|
|
34
|
+
let accessToken = "";
|
|
35
|
+
let refreshToken = "";
|
|
36
|
+
let accessExpiresAt = 0;
|
|
37
|
+
try {
|
|
38
|
+
const raw = localStorage.getItem("oai-auth:onboard");
|
|
39
|
+
const auth = raw ? JSON.parse(raw) : null;
|
|
40
|
+
if (typeof auth?.accessToken === "string") accessToken = auth.accessToken;
|
|
41
|
+
if (typeof auth?.refreshToken === "string") refreshToken = auth.refreshToken;
|
|
42
|
+
if (typeof auth?.accessToken === "string") {
|
|
43
|
+
const parts = auth.accessToken.split(".");
|
|
44
|
+
if (parts[1]) {
|
|
45
|
+
const payload = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
46
|
+
if (typeof payload?.exp === "number") accessExpiresAt = payload.exp > 1e12 ? payload.exp : payload.exp * 1000;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
} catch {}
|
|
50
|
+
if (!accessToken) return { code: "login-required", error: "请先在已打开的 Ego Lite 页面登录 OpenAI Platform,登录成功后返回插件再次点击同步" };
|
|
51
|
+
|
|
52
|
+
const login = await request("https://api.openai.com/v1/dashboard/onboarding/login", {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { Authorization: "Bearer " + accessToken, "Content-Type": "application/json" },
|
|
55
|
+
body: "{}",
|
|
56
|
+
});
|
|
57
|
+
const loginResult = await readJson(login);
|
|
58
|
+
if (login.status === 401 || login.status === 403) {
|
|
59
|
+
return { code: "login-required", error: "OpenAI Platform 登录已失效,请在已打开的页面重新登录后再次同步" };
|
|
60
|
+
}
|
|
61
|
+
if (!login.ok || !loginResult.body) {
|
|
62
|
+
return { code: "login-exchange-failed", error: "OpenAI 登录态兑换失败(HTTP " + login.status + "),请稍后重试" };
|
|
63
|
+
}
|
|
64
|
+
const sessionKey = loginResult.body?.user?.session?.sensitive_id;
|
|
65
|
+
if (typeof sessionKey !== "string" || !sessionKey.startsWith("sess-")) {
|
|
66
|
+
return { code: "session-missing", error: "OpenAI 登录响应未包含有效会话,请重新同步登录态" };
|
|
67
|
+
}
|
|
68
|
+
const orgs = Array.isArray(loginResult.body?.user?.orgs?.data) ? loginResult.body.user.orgs.data : [];
|
|
69
|
+
const org = orgs.find(item => item.personal) || orgs[0];
|
|
70
|
+
const organizationId = typeof org?.id === "string" ? org.id : "";
|
|
71
|
+
const billing = await request("https://api.openai.com/v1/dashboard/billing/credit_grants", {
|
|
72
|
+
method: "GET",
|
|
73
|
+
headers: {
|
|
74
|
+
Authorization: "Bearer " + sessionKey,
|
|
75
|
+
Accept: "application/json",
|
|
76
|
+
...(organizationId ? { "OpenAI-Organization": organizationId } : {}),
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
const billingResult = await readJson(billing);
|
|
80
|
+
if (!billing.ok || !billingResult.body) {
|
|
81
|
+
return { code: billing.status === 401 || billing.status === 403 ? "login-required" : "billing-failed", error: billing.status === 401 || billing.status === 403 ? "OpenAI 会话已失效,请在打开的页面重新登录后再次同步" : "OpenAI 余额读取失败(HTTP " + billing.status + "),请稍后重试" };
|
|
82
|
+
}
|
|
83
|
+
const body = billingResult.body;
|
|
84
|
+
if (body.total_granted === undefined || body.total_used === undefined) {
|
|
85
|
+
return { code: "billing-shape", error: "OpenAI 余额响应格式已变化,请稍后重试" };
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
ok: true,
|
|
89
|
+
sessionKey,
|
|
90
|
+
organizationId,
|
|
91
|
+
accessToken,
|
|
92
|
+
refreshToken,
|
|
93
|
+
accessExpiresAt,
|
|
94
|
+
balance: body,
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const waitForAuth = async () => {
|
|
100
|
+
try {
|
|
101
|
+
await page.waitForFunction(() => {
|
|
102
|
+
if (location.hostname === "auth.openai.com") {
|
|
103
|
+
return !location.pathname.includes("log-in") && !location.pathname.includes("login");
|
|
104
|
+
}
|
|
105
|
+
return Boolean(localStorage.getItem("oai-auth:onboard"));
|
|
106
|
+
}, undefined, { timeout: 12000 });
|
|
107
|
+
} catch {}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// Platform can redirect or reload while its OIDC bootstrap is completing.
|
|
111
|
+
// Retry the read in the same Page instead of treating a navigation as logout.
|
|
112
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
113
|
+
result = { sessionKey: null, organizationId: "", balance: null, error: "", code: "" };
|
|
114
|
+
try {
|
|
115
|
+
const currentUrl = await page.url().catch(() => "");
|
|
116
|
+
if (!currentUrl.startsWith("https://auth.openai.com/")) {
|
|
117
|
+
await page.goto("https://platform.openai.com/home", { timeout: 30000 });
|
|
118
|
+
}
|
|
119
|
+
await waitForAuth();
|
|
120
|
+
if ((await page.url()).startsWith("https://auth.openai.com/")) {
|
|
121
|
+
await page.goto("https://platform.openai.com/home", { timeout: 30000 });
|
|
122
|
+
await waitForAuth();
|
|
123
|
+
}
|
|
124
|
+
const payload = await readBalance();
|
|
125
|
+
Object.assign(result, payload);
|
|
126
|
+
if (result.ok || result.code === "login-required") break;
|
|
127
|
+
if (attempt < 2) {
|
|
128
|
+
await page.waitForTimeout(800);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
} catch (error) {
|
|
132
|
+
result.code = "browser-network";
|
|
133
|
+
result.error = error?.name === "AbortError"
|
|
134
|
+
? "OpenAI 页面网络请求超时(20 秒),请检查 Ego Lite 的网络或代理后重试"
|
|
135
|
+
: String(error?.message || error);
|
|
136
|
+
if (attempt < 2) {
|
|
137
|
+
await page.waitForTimeout(800);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (result.ok) {
|
|
144
|
+
await task.finish({ keep: [] }).catch(() => {});
|
|
145
|
+
} else if (result.code === "login-required" && ALLOW_HANDOFF) {
|
|
146
|
+
let handedOff = false;
|
|
147
|
+
try {
|
|
148
|
+
await page.goto("https://auth.openai.com/log-in", { timeout: 30000 });
|
|
149
|
+
const loginUrl = await page.url();
|
|
150
|
+
if (!loginUrl.startsWith("https://auth.openai.com/")) throw new Error("login page unavailable");
|
|
151
|
+
await task.handOff();
|
|
152
|
+
handedOff = true;
|
|
153
|
+
result.needsLogin = true;
|
|
154
|
+
result.taskSpaceId = task.spaceId;
|
|
155
|
+
} catch {}
|
|
156
|
+
if (!handedOff) {
|
|
157
|
+
result.code = "handoff-failed";
|
|
158
|
+
result.needsLogin = false;
|
|
159
|
+
result.error = "无法打开 OpenAI 登录页,请在 Ego Lite 手动登录 platform.openai.com 后重试";
|
|
160
|
+
await task.finish({ keep: [] }).catch(() => {});
|
|
161
|
+
}
|
|
162
|
+
} else {
|
|
163
|
+
await task.finish({ keep: [] }).catch(() => {});
|
|
164
|
+
}
|
|
165
|
+
console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
package/package.json
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
"name": "dsh-codex-credit-hub",
|
|
3
3
|
"displayName": "Codex Credit Hub",
|
|
4
4
|
"description": "Displays live Codex rate limits and OpenAI / Codex API credit balances above the account avatar in DeepSeek Harness.",
|
|
5
|
-
"version": "1.
|
|
5
|
+
"version": "1.2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "index.js",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": "^22.19.0 || >=24.0.0"
|
|
10
10
|
},
|
|
11
11
|
"scripts": {
|
|
12
|
-
"check": "node --check index.js && node --check client.js"
|
|
12
|
+
"check": "node --check index.js && node --check openai-sync.inc.js && node --check client.js"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {},
|
|
15
15
|
"peerDependencies": {
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"files": [
|
|
32
32
|
"index.js",
|
|
33
|
+
"openai-sync.inc.js",
|
|
33
34
|
"client.js",
|
|
34
35
|
"cordis.patch.yml",
|
|
35
36
|
"locale/*.json",
|