dsh-codex-credit-hub 1.1.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 +9 -6
- package/client.js +6 -3
- package/index.js +616 -43
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/openai-sync.inc.js +69 -34
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -13,10 +13,11 @@ 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
|
-
- 新设备未登录时会保留 OpenAI 登录页;完成登录后,再点击一次「同步 OpenAI 登录态」即可继续。
|
|
20
|
+
- 会话过期时优先在后台续期;只有刷新令牌失效或首次连接时,才需要用户主动点击「同步 OpenAI 登录态」。
|
|
20
21
|
- 临时会话只保存到 DSH 凭证库,不返回给界面或 Agent 工具;默认本地凭证文件在 POSIX 系统仅当前 OS 用户可读,但并非加密存储。卸载插件会取消同步并丢弃内存状态;删除凭证请在 DSH 凭证管理中操作。
|
|
21
22
|
|
|
22
23
|
### Agent 工具
|
|
@@ -49,7 +50,7 @@ dsh-codex-credit-hub
|
|
|
49
50
|
指定版本安装(避免包管理器的最新版本观察期影响):
|
|
50
51
|
|
|
51
52
|
```text
|
|
52
|
-
dsh-codex-credit-hub@1.
|
|
53
|
+
dsh-codex-credit-hub@1.2.0
|
|
53
54
|
```
|
|
54
55
|
|
|
55
56
|
### 本地目录安装
|
|
@@ -65,7 +66,9 @@ dsh-codex-credit-hub@1.1.0
|
|
|
65
66
|
|
|
66
67
|
## 运行前提与限制
|
|
67
68
|
|
|
68
|
-
-
|
|
69
|
-
-
|
|
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 登录或删除该凭证后,需要重新连接。
|
|
70
73
|
- OpenAI Platform 的 `onboarding/login` 和 `credit_grants` 属于网页端接口,不是 OpenAI 面向普通 API Key 的公开余额 API;如果 OpenAI 调整接口,插件会显示同步失败并保留手动重试入口。
|
|
71
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) => {
|
|
@@ -237,6 +239,7 @@ window.__ModuleLoader__.load({
|
|
|
237
239
|
h('div', null, h('div', { className: 'cxh-factLabel' }, t('totalUsed')), h('div', { className: 'cxh-factValue' }, formatUsd(quota.totalUsedUsd))),
|
|
238
240
|
nextExpiry && h('div', null, h('div', { className: 'cxh-factLabel' }, t('nextExpiry')), h('div', { className: 'cxh-factValue' }, formatResetTime(nextExpiry.expiresAtMs)))),
|
|
239
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'))))),
|
|
242
|
+
quota && state.stale && h('p', { className: 'cxh-help', role: 'status' }, t('stale')),
|
|
240
243
|
quota && state.error && !actionError && h('p', { className: 'cxh-error', role: 'status' }, state.error),
|
|
241
244
|
!quota && state.status === 'loading' && h('div', { className: 'cxh-loading' }, t('loading')),
|
|
242
245
|
!quota && state.status !== 'loading' && !actionError && h('p', { className: state.status === 'unauthorized' ? 'cxh-help' : 'cxh-error', role: 'status' }, state.error || t('error')),
|
package/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
|
-
import { readFileSync } from 'node:fs'
|
|
3
|
-
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
3
|
+
import { mkdir, readFile, rm } from 'node:fs/promises'
|
|
4
4
|
import { homedir } from 'node:os'
|
|
5
5
|
import { delimiter, join } from 'node:path'
|
|
6
|
+
import { randomUUID } from 'node:crypto'
|
|
6
7
|
import z from '@deepseek-ai/schemastery'
|
|
7
8
|
import { credentialKey } from '@deepseek-ai/dsh-credentials'
|
|
8
9
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
@@ -16,6 +17,10 @@ export const RECORD_ID_API = 'codex-api'
|
|
|
16
17
|
const CODEX_WHAM_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'
|
|
17
18
|
const CODEX_WEB_URL = 'https://chatgpt.com/codex/settings/usage'
|
|
18
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'
|
|
19
24
|
const OPENAI_API_WEB_URL = 'https://platform.openai.com/home'
|
|
20
25
|
const OPENAI_PLATFORM_HOME_URL = 'https://platform.openai.com/home'
|
|
21
26
|
const OPENAI_BROWSER_SYNC_COOLDOWN_MS = 60_000
|
|
@@ -515,12 +520,13 @@ async function fetchOpenAiCreditBalanceFromBody(body, organizationId = '') {
|
|
|
515
520
|
let openAiBrowserSyncInFlight = null
|
|
516
521
|
let openAiBrowserSyncLastAttempt = 0
|
|
517
522
|
let openAiBrowserSyncLastError = ''
|
|
523
|
+
let openAiBrowserSyncLastErrorCode = ''
|
|
518
524
|
let openAiLoginPending = null
|
|
519
525
|
const OPENAI_SYNC_SCRIPT = readFileSync(new URL('./openai-sync.inc.js', import.meta.url), 'utf8')
|
|
520
526
|
|
|
521
|
-
async function syncOpenAiSessionFromEgoBrowserOnce(signal) {
|
|
527
|
+
async function syncOpenAiSessionFromEgoBrowserOnce(signal, allowHandoff = false) {
|
|
522
528
|
return await new Promise((resolve) => {
|
|
523
|
-
const script = OPENAI_SYNC_SCRIPT
|
|
529
|
+
const script = OPENAI_SYNC_SCRIPT.replace('__ALLOW_HANDOFF__', allowHandoff ? 'true' : 'false')
|
|
524
530
|
|
|
525
531
|
const envPath = [
|
|
526
532
|
process.env.PATH ?? '',
|
|
@@ -563,8 +569,9 @@ async function syncOpenAiSessionFromEgoBrowserOnce(signal) {
|
|
|
563
569
|
child.stderr.on('data', chunk => { stderr += chunk.toString('utf8') })
|
|
564
570
|
child.on('error', error => {
|
|
565
571
|
finish({
|
|
572
|
+
code: error?.code === 'ENOENT' ? 'no-ego-browser' : 'ego-launch-failed',
|
|
566
573
|
error: error?.code === 'ENOENT'
|
|
567
|
-
? '未检测到 Ego Lite / ego-browser
|
|
574
|
+
? '未检测到 Ego Lite / ego-browser'
|
|
568
575
|
: scrubSecrets('无法启动 Ego Lite: ' + error.message),
|
|
569
576
|
})
|
|
570
577
|
})
|
|
@@ -629,7 +636,398 @@ function subscribeOpenAiBrowserSync(entry, signal) {
|
|
|
629
636
|
})
|
|
630
637
|
}
|
|
631
638
|
|
|
632
|
-
|
|
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
|
|
633
1031
|
if (openAiBrowserSyncInFlight) return await subscribeOpenAiBrowserSync(openAiBrowserSyncInFlight, signal)
|
|
634
1032
|
if (!force && openAiLoginPending) {
|
|
635
1033
|
return {
|
|
@@ -639,30 +1037,53 @@ async function syncOpenAiSessionFromEgoBrowser(force = false, signal) {
|
|
|
639
1037
|
error: 'OpenAI 登录页已打开,请先完成登录,再点击「同步 OpenAI 登录态」;后台不会打断登录',
|
|
640
1038
|
}
|
|
641
1039
|
}
|
|
642
|
-
|
|
643
|
-
|
|
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 }
|
|
644
1045
|
}
|
|
645
1046
|
openAiBrowserSyncLastAttempt = Date.now()
|
|
646
1047
|
openAiBrowserSyncLastError = ''
|
|
1048
|
+
openAiBrowserSyncLastErrorCode = ''
|
|
647
1049
|
const entry = {
|
|
648
1050
|
controller: new AbortController(),
|
|
649
1051
|
subscribers: new Set(),
|
|
650
1052
|
abortTimer: null,
|
|
651
1053
|
promise: null,
|
|
652
1054
|
}
|
|
653
|
-
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
|
+
})()
|
|
654
1075
|
.then(result => {
|
|
655
|
-
// A caller-local cancellation is not the shared task's outcome. Record
|
|
656
|
-
// only the browser result, and clear stale errors after a real success.
|
|
657
1076
|
openAiBrowserSyncLastError = result?.error ? scrubSecrets(result.error) : ''
|
|
1077
|
+
openAiBrowserSyncLastErrorCode = result?.error ? (result?.code || 'sync-failed') : ''
|
|
658
1078
|
openAiLoginPending = result?.needsLogin && result?.taskSpaceId
|
|
659
1079
|
? { taskSpaceId: result.taskSpaceId }
|
|
660
1080
|
: null
|
|
661
1081
|
return result
|
|
662
1082
|
})
|
|
663
1083
|
.catch(() => {
|
|
664
|
-
const result = { error: 'OpenAI 浏览器同步失败,请稍后重试' }
|
|
1084
|
+
const result = { code: 'sync-failed', error: 'OpenAI 浏览器同步失败,请稍后重试' }
|
|
665
1085
|
openAiBrowserSyncLastError = result.error
|
|
1086
|
+
openAiBrowserSyncLastErrorCode = result.code
|
|
666
1087
|
return result
|
|
667
1088
|
})
|
|
668
1089
|
.finally(() => {
|
|
@@ -800,6 +1221,8 @@ export class CodexApiQuotaService {
|
|
|
800
1221
|
this.generation = 0
|
|
801
1222
|
this.disposed = false
|
|
802
1223
|
this.controllers = new Set()
|
|
1224
|
+
this.failureCount = 0
|
|
1225
|
+
this.oauthInFlight = null
|
|
803
1226
|
}
|
|
804
1227
|
|
|
805
1228
|
dispose() {
|
|
@@ -819,25 +1242,81 @@ export class CodexApiQuotaService {
|
|
|
819
1242
|
}
|
|
820
1243
|
|
|
821
1244
|
commit(generation, state) {
|
|
1245
|
+
if (state?.status === 'ok' && !state.error) this.failureCount = 0
|
|
822
1246
|
if (generation === this.generation) this.cached = state
|
|
823
1247
|
return this.cached ?? state
|
|
824
1248
|
}
|
|
825
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
|
+
|
|
826
1276
|
async readStoredSession() {
|
|
827
1277
|
try {
|
|
828
1278
|
const record = await this.ctx.credentials.readRecord(this.key)
|
|
829
1279
|
if (record?.kind !== 'grant' || !record.payload || typeof record.payload !== 'object') return null
|
|
830
1280
|
const sessionKey = normalizeSecretInput(record.payload.sessionKey)
|
|
831
|
-
|
|
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)
|
|
832
1285
|
return {
|
|
833
1286
|
sessionKey,
|
|
834
1287
|
organizationId: typeof record.payload.organizationId === 'string' ? record.payload.organizationId.trim() : '',
|
|
1288
|
+
accessToken,
|
|
1289
|
+
refreshToken,
|
|
1290
|
+
accessExpiresAt: Number.isFinite(expires) ? expires : 0,
|
|
835
1291
|
}
|
|
836
1292
|
} catch {
|
|
837
1293
|
return null
|
|
838
1294
|
}
|
|
839
1295
|
}
|
|
840
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
|
+
|
|
841
1320
|
async getQuota(options = {}) {
|
|
842
1321
|
const { force = false, signal } = options
|
|
843
1322
|
if (!force && this.cached && this.cached.status === 'ok') {
|
|
@@ -882,59 +1361,150 @@ export class CodexApiQuotaService {
|
|
|
882
1361
|
|
|
883
1362
|
async _resolveQuota(signal, generation) {
|
|
884
1363
|
const stored = await this.readStoredSession()
|
|
885
|
-
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-')) {
|
|
886
1375
|
const result = await fetchOpenAiCreditBalance(stored.sessionKey, stored.organizationId, signal)
|
|
887
1376
|
if (result.ok) {
|
|
888
1377
|
return this.commit(generation, {
|
|
889
1378
|
status: 'ok',
|
|
890
|
-
source: 'openai-platform-
|
|
1379
|
+
source: 'openai-platform-session',
|
|
891
1380
|
quota: result.data,
|
|
892
1381
|
preferences: this.getPreferences(),
|
|
893
1382
|
})
|
|
894
1383
|
}
|
|
895
|
-
// Browser networking can use a system/VPN proxy that Node's fetch does
|
|
896
|
-
// not inherit. On transport failures, retry through Platform's page.
|
|
897
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) {
|
|
898
1392
|
return this.commit(generation, {
|
|
899
|
-
status: '
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
webUrl: OPENAI_API_WEB_URL,
|
|
1393
|
+
status: 'ok',
|
|
1394
|
+
source: 'openai-platform-oauth',
|
|
1395
|
+
quota: oauth.data,
|
|
903
1396
|
preferences: this.getPreferences(),
|
|
904
1397
|
})
|
|
905
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
|
+
}
|
|
906
1402
|
}
|
|
907
1403
|
|
|
908
|
-
//
|
|
909
|
-
//
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
webUrl: OPENAI_API_WEB_URL,
|
|
917
|
-
preferences: this.getPreferences(),
|
|
918
|
-
})
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
const synced = await this.syncFromBrowser({ internal: true, signal, expectedGeneration: generation })
|
|
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
|
+
})
|
|
922
1412
|
if (synced.ok) return synced.state
|
|
923
|
-
return this.
|
|
1413
|
+
return this.commitFailure(generation, {
|
|
924
1414
|
status: synced.code === 'login-required' ? 'unauthorized' : 'error',
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
webUrl: OPENAI_API_WEB_URL,
|
|
928
|
-
preferences: this.getPreferences(),
|
|
1415
|
+
code: synced.code,
|
|
1416
|
+
error: synced.error || 'OpenAI Platform 登录态已过期,请点击「同步 OpenAI 登录态」重新登录',
|
|
929
1417
|
})
|
|
930
1418
|
}
|
|
931
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
|
|
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 令牌已失效,请重新同步' }
|
|
1498
|
+
}
|
|
1499
|
+
|
|
932
1500
|
async syncFromBrowser(options = {}) {
|
|
933
1501
|
const generation = options.expectedGeneration ?? this.generation
|
|
934
1502
|
if (generation !== this.generation || this.disposed) {
|
|
935
1503
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
936
1504
|
}
|
|
937
|
-
const synced = await
|
|
1505
|
+
const synced = await syncOpenAiSessionFromBrowser(Boolean(options.force), options.signal, {
|
|
1506
|
+
allowSystemBrowser: options.allowSystemBrowser !== false,
|
|
1507
|
+
})
|
|
938
1508
|
if (generation !== this.generation || this.disposed) {
|
|
939
1509
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
940
1510
|
}
|
|
@@ -981,8 +1551,11 @@ export class CodexApiQuotaService {
|
|
|
981
1551
|
sessionKey,
|
|
982
1552
|
organizationId,
|
|
983
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
|
|
984
1557
|
try {
|
|
985
|
-
await this.
|
|
1558
|
+
await this.saveCredentials(payload)
|
|
986
1559
|
} catch (error) {
|
|
987
1560
|
return { ok: false, error: '会话已验证,但保存到 DSH 凭证库失败: ' + scrubSecrets(error instanceof Error ? error.message : String(error)) }
|
|
988
1561
|
}
|
|
@@ -990,7 +1563,7 @@ export class CodexApiQuotaService {
|
|
|
990
1563
|
|
|
991
1564
|
const state = {
|
|
992
1565
|
status: 'ok',
|
|
993
|
-
source: 'openai-platform-browser',
|
|
1566
|
+
source: session.source || 'openai-platform-browser',
|
|
994
1567
|
quota: probe.data,
|
|
995
1568
|
preferences: this.getPreferences(),
|
|
996
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
|
}
|
package/openai-sync.inc.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const ALLOW_HANDOFF = __ALLOW_HANDOFF__;
|
|
1
2
|
const spaces = await listTaskSpaces();
|
|
2
3
|
const existing = spaces.find(space => space.name === "codex-credit-openai-session");
|
|
3
4
|
let task;
|
|
@@ -13,28 +14,9 @@ if (existing?.ownership === "agentDelegatedToUser") {
|
|
|
13
14
|
const pages = await task.pages();
|
|
14
15
|
const page = pages[0] ?? await task.adopt((await task.tabs())[0].page);
|
|
15
16
|
let result = { sessionKey: null, organizationId: "", balance: null, error: "", code: "" };
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
// page. Platform/OIDC completion is awaited below before reading storage.
|
|
20
|
-
if (!currentUrl.startsWith("https://auth.openai.com/")) {
|
|
21
|
-
await page.goto("https://platform.openai.com/home", { timeout: 30000 });
|
|
22
|
-
}
|
|
23
|
-
// Wait for Platform's own OIDC bootstrap instead of reading a CDP response
|
|
24
|
-
// before Network.loadingFinished. Slow first loads are normal on new devices.
|
|
25
|
-
try {
|
|
26
|
-
await page.waitForFunction(() => {
|
|
27
|
-
if (location.hostname === "auth.openai.com") {
|
|
28
|
-
return !location.pathname.includes("log-in") && !location.pathname.includes("login");
|
|
29
|
-
}
|
|
30
|
-
return Boolean(localStorage.getItem("oai-auth:onboard"));
|
|
31
|
-
}, undefined, { timeout: 12000 });
|
|
32
|
-
} catch {}
|
|
33
|
-
if ((await page.url()).startsWith("https://auth.openai.com/")) {
|
|
34
|
-
await page.goto("https://platform.openai.com/home", { timeout: 30000 });
|
|
35
|
-
await page.waitForFunction(() => Boolean(localStorage.getItem("oai-auth:onboard")), undefined, { timeout: 12000 }).catch(() => {});
|
|
36
|
-
}
|
|
37
|
-
const payload = await page.evaluate(async () => {
|
|
17
|
+
|
|
18
|
+
const readBalance = async () => {
|
|
19
|
+
return await page.evaluate(async () => {
|
|
38
20
|
const request = async (url, options) => {
|
|
39
21
|
const controller = new AbortController();
|
|
40
22
|
const timer = setTimeout(() => controller.abort(), 20000);
|
|
@@ -50,10 +32,20 @@ try {
|
|
|
50
32
|
catch { return { response, body: null }; }
|
|
51
33
|
};
|
|
52
34
|
let accessToken = "";
|
|
35
|
+
let refreshToken = "";
|
|
36
|
+
let accessExpiresAt = 0;
|
|
53
37
|
try {
|
|
54
38
|
const raw = localStorage.getItem("oai-auth:onboard");
|
|
55
39
|
const auth = raw ? JSON.parse(raw) : null;
|
|
56
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
|
+
}
|
|
57
49
|
} catch {}
|
|
58
50
|
if (!accessToken) return { code: "login-required", error: "请先在已打开的 Ego Lite 页面登录 OpenAI Platform,登录成功后返回插件再次点击同步" };
|
|
59
51
|
|
|
@@ -92,22 +84,65 @@ try {
|
|
|
92
84
|
if (body.total_granted === undefined || body.total_used === undefined) {
|
|
93
85
|
return { code: "billing-shape", error: "OpenAI 余额响应格式已变化,请稍后重试" };
|
|
94
86
|
}
|
|
95
|
-
return {
|
|
87
|
+
return {
|
|
88
|
+
ok: true,
|
|
89
|
+
sessionKey,
|
|
90
|
+
organizationId,
|
|
91
|
+
accessToken,
|
|
92
|
+
refreshToken,
|
|
93
|
+
accessExpiresAt,
|
|
94
|
+
balance: body,
|
|
95
|
+
};
|
|
96
96
|
});
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
+
}
|
|
103
141
|
}
|
|
104
|
-
|
|
105
|
-
// hands control to the user, who can log in and explicitly retry this sync.
|
|
142
|
+
|
|
106
143
|
if (result.ok) {
|
|
107
144
|
await task.finish({ keep: [] }).catch(() => {});
|
|
108
|
-
} else if (result.code === "login-required") {
|
|
109
|
-
// Land on the real login page, not an empty Platform shell, when there is
|
|
110
|
-
// no OIDC state. The user sees exactly what action is required.
|
|
145
|
+
} else if (result.code === "login-required" && ALLOW_HANDOFF) {
|
|
111
146
|
let handedOff = false;
|
|
112
147
|
try {
|
|
113
148
|
await page.goto("https://auth.openai.com/log-in", { timeout: 30000 });
|
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": {
|