dsh-codex-credit-hub 1.0.0 → 1.1.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 +7 -5
- package/client.js +16 -6
- package/index.js +75 -62
- package/openai-sync.inc.js +130 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -13,10 +13,11 @@ DeepSeek Harness 扩展插件,在左侧边栏底部、头像上方显示 **Cod
|
|
|
13
13
|
### Codex API
|
|
14
14
|
|
|
15
15
|
- **只使用 OpenAI Platform 登录态,不接受、不读取、不保存 API Key。**
|
|
16
|
-
- 插件通过本机 `ego-browser`
|
|
16
|
+
- 插件通过本机 Ego Lite 的 `ego-browser` 复用 `platform.openai.com` 登录态,在页面内完成 `POST /v1/dashboard/onboarding/login` 会话兑换和 `GET /v1/dashboard/billing/credit_grants` 余额校验。
|
|
17
17
|
- 展示与 `https://platform.openai.com/home` 一致的真实余额、总额度、已用额度、剩余百分比和最近 grant 到期时间。
|
|
18
|
-
-
|
|
19
|
-
-
|
|
18
|
+
- 会话过期、失效或 Node 网络请求超时/失败时自动通过浏览器重新同步;浏览器网络可使用系统代理或 VPN,降低仅 Node 请求超时的影响。
|
|
19
|
+
- 新设备未登录时会保留 OpenAI 登录页;完成登录后,再点击一次「同步 OpenAI 登录态」即可继续。
|
|
20
|
+
- 临时会话只保存到 DSH 凭证库,不返回给界面或 Agent 工具;默认本地凭证文件在 POSIX 系统仅当前 OS 用户可读,但并非加密存储。卸载插件会取消同步并丢弃内存状态;删除凭证请在 DSH 凭证管理中操作。
|
|
20
21
|
|
|
21
22
|
### Agent 工具
|
|
22
23
|
|
|
@@ -48,7 +49,7 @@ dsh-codex-credit-hub
|
|
|
48
49
|
指定版本安装(避免包管理器的最新版本观察期影响):
|
|
49
50
|
|
|
50
51
|
```text
|
|
51
|
-
dsh-codex-credit-hub@1.
|
|
52
|
+
dsh-codex-credit-hub@1.1.0
|
|
52
53
|
```
|
|
53
54
|
|
|
54
55
|
### 本地目录安装
|
|
@@ -64,6 +65,7 @@ dsh-codex-credit-hub@1.0.0
|
|
|
64
65
|
|
|
65
66
|
## 运行前提与限制
|
|
66
67
|
|
|
67
|
-
- Codex API
|
|
68
|
+
- Codex API 自动同步需要安装并启动 [Ego Lite](https://lite.ego.app/),完成其初始设置,使 `ego-browser` 命令可用。
|
|
69
|
+
- 同步依赖 Ego Lite 中的 OpenAI Platform 登录态;它与系统默认浏览器、Chrome 的登录状态不是同一份。如果 Chrome 已登录但 Ego Lite 未登录,插件会打开登录页,登录后需再次点击同步。
|
|
68
70
|
- OpenAI Platform 的 `onboarding/login` 和 `credit_grants` 属于网页端接口,不是 OpenAI 面向普通 API Key 的公开余额 API;如果 OpenAI 调整接口,插件会显示同步失败并保留手动重试入口。
|
|
69
71
|
- Codex 订阅额度与 OpenAI API 预付/赠送余额是不同账户体系,插件分别展示,不互相推算。
|
package/client.js
CHANGED
|
@@ -29,7 +29,7 @@ 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
|
-
apiHint: '
|
|
32
|
+
apiHint: 'Requires Ego Lite. If the OpenAI login page opens, sign in there, then click Sync OpenAI login again. No API key is required.',
|
|
33
33
|
cliHint: 'Reads ~/.codex/auth.json (read-only) or `codex app-server`. Run `codex login` in terminal to sign in.',
|
|
34
34
|
}
|
|
35
35
|
const zh = {
|
|
@@ -42,7 +42,7 @@ window.__ModuleLoader__.load({
|
|
|
42
42
|
nextExpiry: '最近到期', updated: '更新于', refresh: '刷新', refreshing: '刷新中…',
|
|
43
43
|
manage: '管理用量', close: '关闭额度详情', error: '暂时无法读取 Codex 额度', retry: '重试',
|
|
44
44
|
syncBrowser: '同步 OpenAI 登录态', syncingBrowser: '同步中…',
|
|
45
|
-
apiHint: '
|
|
45
|
+
apiHint: '需要安装 Ego Lite。若打开 OpenAI 登录页,请先完成登录,再点击一次「同步 OpenAI 登录态」;无需输入 API Key。',
|
|
46
46
|
cliHint: '自动只读读取 ~/.codex/auth.json 或 codex app-server;若未登录请在终端执行 `codex login`。',
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -84,8 +84,18 @@ window.__ModuleLoader__.load({
|
|
|
84
84
|
}
|
|
85
85
|
const mutate = async (mutEndpoint, payload) => {
|
|
86
86
|
const current = ++generation
|
|
87
|
+
const previous = snapshot
|
|
88
|
+
emit({ ...snapshot, error: undefined })
|
|
87
89
|
const result = await callApi(mutEndpoint, payload)
|
|
88
|
-
if (!result.ok)
|
|
90
|
+
if (!result.ok) {
|
|
91
|
+
const message = result.error.message
|
|
92
|
+
if (!disposed && current === generation) {
|
|
93
|
+
const next = previous.status === 'ok' ? { ...previous, error: message } : { ...previous, status: previous.status === 'unauthorized' ? 'unauthorized' : 'error', error: message }
|
|
94
|
+
emit(next)
|
|
95
|
+
schedule(next)
|
|
96
|
+
}
|
|
97
|
+
throw new Error(message)
|
|
98
|
+
}
|
|
89
99
|
if (disposed || current !== generation) return result.value
|
|
90
100
|
emit(result.value); schedule(result.value)
|
|
91
101
|
return result.value
|
|
@@ -227,15 +237,15 @@ window.__ModuleLoader__.load({
|
|
|
227
237
|
h('div', null, h('div', { className: 'cxh-factLabel' }, t('totalUsed')), h('div', { className: 'cxh-factValue' }, formatUsd(quota.totalUsedUsd))),
|
|
228
238
|
nextExpiry && h('div', null, h('div', { className: 'cxh-factLabel' }, t('nextExpiry')), h('div', { className: 'cxh-factValue' }, formatResetTime(nextExpiry.expiresAtMs)))),
|
|
229
239
|
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.error && h('p', { className: 'cxh-error', role: 'status' }, state.error),
|
|
240
|
+
quota && state.error && !actionError && h('p', { className: 'cxh-error', role: 'status' }, state.error),
|
|
231
241
|
!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')),
|
|
242
|
+
!quota && state.status !== 'loading' && !actionError && h('p', { className: state.status === 'unauthorized' ? 'cxh-help' : 'cxh-error', role: 'status' }, state.error || t('error')),
|
|
233
243
|
actionError && h('p', { className: 'cxh-error', role: 'status' }, actionError),
|
|
234
244
|
!quota && state.status !== 'loading' && h('p', { className: 'cxh-help' }, isCli ? t('cliHint') : t('apiHint')),
|
|
235
245
|
!quota && state.status !== 'loading' && h('div', { className: 'cxh-errorActions' }, isCli
|
|
236
246
|
? h('button', { type: 'button', className: 'cxh-retry', disabled: busy !== '', onClick: refresh }, busy === 'refresh' ? t('refreshing') : t('retry'))
|
|
237
247
|
: 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 }, '↗')),
|
|
248
|
+
quota && h('button', { type: 'button', className: 'cxh-manage', onClick: manage }, h('span', null, t('manage')), h('span', { 'aria-hidden': true }, '↗')),
|
|
239
249
|
), document.body),
|
|
240
250
|
)
|
|
241
251
|
}
|
package/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
2
3
|
import { readFile } from 'node:fs/promises'
|
|
3
4
|
import { homedir } from 'node:os'
|
|
4
5
|
import { delimiter, join } from 'node:path'
|
|
@@ -83,10 +84,14 @@ export function isJwtExpired(token, skewMs = 60_000) {
|
|
|
83
84
|
}
|
|
84
85
|
|
|
85
86
|
function requestFailure(error, label) {
|
|
87
|
+
if (error?.name === 'TimeoutError') {
|
|
88
|
+
return { ok: false, status: 0, network: true, message: `${label} 网络请求超时,请检查网络或代理连接` }
|
|
89
|
+
}
|
|
86
90
|
if (error?.name === 'AbortError') return { ok: false, status: 0, message: `${label} 请求已取消` }
|
|
87
91
|
return {
|
|
88
92
|
ok: false,
|
|
89
93
|
status: 0,
|
|
94
|
+
network: true,
|
|
90
95
|
message: scrubSecrets(`${label} 网络请求失败,请检查网络或代理连接 (${error instanceof Error ? error.message : String(error)})`),
|
|
91
96
|
}
|
|
92
97
|
}
|
|
@@ -447,6 +452,13 @@ async function fetchOpenAiCreditBalance(sessionKey, organizationId = '', signal)
|
|
|
447
452
|
const message = body?.error?.message || body?.message || ('OpenAI Billing 请求失败 (HTTP ' + response.status + ')')
|
|
448
453
|
return { ok: false, status: response.status, message: scrubSecrets(message) }
|
|
449
454
|
}
|
|
455
|
+
return await fetchOpenAiCreditBalanceFromBody(body, organizationId)
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function fetchOpenAiCreditBalanceFromBody(body, organizationId = '') {
|
|
459
|
+
if (!body || typeof body !== 'object') {
|
|
460
|
+
return { ok: false, status: 502, message: 'OpenAI Billing 返回了空响应' }
|
|
461
|
+
}
|
|
450
462
|
if (body.object && body.object !== 'credit_summary') {
|
|
451
463
|
return { ok: false, status: 502, message: 'OpenAI Billing 返回了无法识别的响应格式' }
|
|
452
464
|
}
|
|
@@ -503,49 +515,13 @@ async function fetchOpenAiCreditBalance(sessionKey, organizationId = '', signal)
|
|
|
503
515
|
let openAiBrowserSyncInFlight = null
|
|
504
516
|
let openAiBrowserSyncLastAttempt = 0
|
|
505
517
|
let openAiBrowserSyncLastError = ''
|
|
518
|
+
let openAiLoginPending = null
|
|
519
|
+
const OPENAI_SYNC_SCRIPT = readFileSync(new URL('./openai-sync.inc.js', import.meta.url), 'utf8')
|
|
506
520
|
|
|
507
521
|
async function syncOpenAiSessionFromEgoBrowserOnce(signal) {
|
|
508
522
|
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
|
-
`
|
|
523
|
+
const script = OPENAI_SYNC_SCRIPT
|
|
524
|
+
|
|
549
525
|
const envPath = [
|
|
550
526
|
process.env.PATH ?? '',
|
|
551
527
|
'/usr/local/bin',
|
|
@@ -562,7 +538,6 @@ console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
|
|
562
538
|
let stdout = ''
|
|
563
539
|
let stderr = ''
|
|
564
540
|
let settled = false
|
|
565
|
-
let timer = null
|
|
566
541
|
const finish = (value) => {
|
|
567
542
|
if (settled) return
|
|
568
543
|
settled = true
|
|
@@ -579,33 +554,34 @@ console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
|
|
579
554
|
return
|
|
580
555
|
}
|
|
581
556
|
signal?.addEventListener('abort', onAbort, { once: true })
|
|
582
|
-
timer = setTimeout(() => {
|
|
557
|
+
const timer = setTimeout(() => {
|
|
583
558
|
try { child.kill('SIGKILL') } catch {}
|
|
584
|
-
finish({ error: 'OpenAI 浏览器同步超时(
|
|
585
|
-
},
|
|
559
|
+
finish({ error: 'OpenAI 浏览器同步超时(65 秒),请检查网络或代理后重试' })
|
|
560
|
+
}, 65_000)
|
|
586
561
|
timer.unref?.()
|
|
587
562
|
child.stdout.on('data', chunk => { stdout += chunk.toString('utf8') })
|
|
588
563
|
child.stderr.on('data', chunk => { stderr += chunk.toString('utf8') })
|
|
589
564
|
child.on('error', error => {
|
|
590
565
|
finish({
|
|
591
566
|
error: error?.code === 'ENOENT'
|
|
592
|
-
? '未检测到 ego-browser
|
|
593
|
-
: scrubSecrets(
|
|
567
|
+
? '未检测到 Ego Lite / ego-browser,请先安装 Ego Lite 并完成初始设置后重试'
|
|
568
|
+
: scrubSecrets('无法启动 Ego Lite: ' + error.message),
|
|
594
569
|
})
|
|
595
570
|
})
|
|
596
571
|
child.on('close', () => {
|
|
597
572
|
const output = `${stdout}\n${stderr}`
|
|
598
573
|
const marker = output.lastIndexOf('__CODEX_OPENAI_SYNC__')
|
|
599
574
|
if (marker < 0) {
|
|
600
|
-
finish({ error: 'OpenAI
|
|
575
|
+
finish({ error: 'OpenAI 浏览器同步未完成,请确认 Ego Lite 已启动并可访问 platform.openai.com' })
|
|
601
576
|
return
|
|
602
577
|
}
|
|
603
578
|
try {
|
|
604
579
|
const jsonText = output.slice(marker + '__CODEX_OPENAI_SYNC__'.length).trim().split('\n')[0]
|
|
605
580
|
const parsed = JSON.parse(jsonText)
|
|
581
|
+
if (parsed?.error) parsed.error = scrubSecrets(parsed.error)
|
|
606
582
|
finish(parsed)
|
|
607
583
|
} catch {
|
|
608
|
-
finish({ error: 'OpenAI
|
|
584
|
+
finish({ error: 'OpenAI 浏览器同步返回格式异常,请重试' })
|
|
609
585
|
}
|
|
610
586
|
})
|
|
611
587
|
})
|
|
@@ -655,8 +631,16 @@ function subscribeOpenAiBrowserSync(entry, signal) {
|
|
|
655
631
|
|
|
656
632
|
async function syncOpenAiSessionFromEgoBrowser(force = false, signal) {
|
|
657
633
|
if (openAiBrowserSyncInFlight) return await subscribeOpenAiBrowserSync(openAiBrowserSyncInFlight, signal)
|
|
658
|
-
if (!force &&
|
|
659
|
-
return {
|
|
634
|
+
if (!force && openAiLoginPending) {
|
|
635
|
+
return {
|
|
636
|
+
code: 'login-required',
|
|
637
|
+
needsLogin: true,
|
|
638
|
+
taskSpaceId: openAiLoginPending.taskSpaceId,
|
|
639
|
+
error: 'OpenAI 登录页已打开,请先完成登录,再点击「同步 OpenAI 登录态」;后台不会打断登录',
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (!force && openAiBrowserSyncLastAttempt > 0 && openAiBrowserSyncLastError && Date.now() - openAiBrowserSyncLastAttempt < OPENAI_BROWSER_SYNC_COOLDOWN_MS) {
|
|
643
|
+
return { error: openAiBrowserSyncLastError }
|
|
660
644
|
}
|
|
661
645
|
openAiBrowserSyncLastAttempt = Date.now()
|
|
662
646
|
openAiBrowserSyncLastError = ''
|
|
@@ -668,10 +652,19 @@ async function syncOpenAiSessionFromEgoBrowser(force = false, signal) {
|
|
|
668
652
|
}
|
|
669
653
|
entry.promise = syncOpenAiSessionFromEgoBrowserOnce(entry.controller.signal)
|
|
670
654
|
.then(result => {
|
|
671
|
-
|
|
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
|
+
openAiBrowserSyncLastError = result?.error ? scrubSecrets(result.error) : ''
|
|
658
|
+
openAiLoginPending = result?.needsLogin && result?.taskSpaceId
|
|
659
|
+
? { taskSpaceId: result.taskSpaceId }
|
|
660
|
+
: null
|
|
661
|
+
return result
|
|
662
|
+
})
|
|
663
|
+
.catch(() => {
|
|
664
|
+
const result = { error: 'OpenAI 浏览器同步失败,请稍后重试' }
|
|
665
|
+
openAiBrowserSyncLastError = result.error
|
|
672
666
|
return result
|
|
673
667
|
})
|
|
674
|
-
.catch(() => ({ error: 'OpenAI 浏览器同步失败,请稍后重试' }))
|
|
675
668
|
.finally(() => {
|
|
676
669
|
if (entry.abortTimer) {
|
|
677
670
|
clearTimeout(entry.abortTimer)
|
|
@@ -899,9 +892,9 @@ export class CodexApiQuotaService {
|
|
|
899
892
|
preferences: this.getPreferences(),
|
|
900
893
|
})
|
|
901
894
|
}
|
|
902
|
-
//
|
|
903
|
-
//
|
|
904
|
-
if (result.status !== 401 && result.status !== 403) {
|
|
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
|
+
if (result.status !== 401 && result.status !== 403 && !result.network) {
|
|
905
898
|
return this.commit(generation, {
|
|
906
899
|
status: 'error',
|
|
907
900
|
error: result.message,
|
|
@@ -912,10 +905,23 @@ export class CodexApiQuotaService {
|
|
|
912
905
|
}
|
|
913
906
|
}
|
|
914
907
|
|
|
908
|
+
// Opening a browser is an explicit user action, not a startup side effect.
|
|
909
|
+
// Stored sessions may recover automatically; first-time setup uses the
|
|
910
|
+
// visible "Sync OpenAI login" button in the popover.
|
|
911
|
+
if (!stored) {
|
|
912
|
+
return this.commit(generation, {
|
|
913
|
+
status: 'unauthorized',
|
|
914
|
+
error: '尚未连接 OpenAI Platform。点击「同步 OpenAI 登录态」开始连接;无需输入 API Key',
|
|
915
|
+
canSync: true,
|
|
916
|
+
webUrl: OPENAI_API_WEB_URL,
|
|
917
|
+
preferences: this.getPreferences(),
|
|
918
|
+
})
|
|
919
|
+
}
|
|
920
|
+
|
|
915
921
|
const synced = await this.syncFromBrowser({ internal: true, signal, expectedGeneration: generation })
|
|
916
922
|
if (synced.ok) return synced.state
|
|
917
923
|
return this.commit(generation, {
|
|
918
|
-
status: 'unauthorized',
|
|
924
|
+
status: synced.code === 'login-required' ? 'unauthorized' : 'error',
|
|
919
925
|
error: synced.error || '未能同步 OpenAI Platform 登录态,请点击同步后重试',
|
|
920
926
|
canSync: true,
|
|
921
927
|
webUrl: OPENAI_API_WEB_URL,
|
|
@@ -933,7 +939,7 @@ export class CodexApiQuotaService {
|
|
|
933
939
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
934
940
|
}
|
|
935
941
|
if (!synced?.sessionKey) {
|
|
936
|
-
return { ok: false, error: scrubSecrets(synced?.error || '未能同步 OpenAI Platform 登录态') }
|
|
942
|
+
return { ok: false, code: synced?.code || '', error: scrubSecrets(synced?.error || '未能同步 OpenAI Platform 登录态') }
|
|
937
943
|
}
|
|
938
944
|
return await this.saveSession(synced, { ...options, expectedGeneration: generation })
|
|
939
945
|
}
|
|
@@ -943,7 +949,10 @@ export class CodexApiQuotaService {
|
|
|
943
949
|
return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
944
950
|
}
|
|
945
951
|
const generation = ++this.generation
|
|
946
|
-
if (!options.internal)
|
|
952
|
+
if (!options.internal) {
|
|
953
|
+
this.inFlight?.abort()
|
|
954
|
+
openAiLoginPending = null
|
|
955
|
+
}
|
|
947
956
|
const sessionKey = normalizeSecretInput(session.sessionKey)
|
|
948
957
|
const organizationId = typeof session.organizationId === 'string' ? session.organizationId.trim() : ''
|
|
949
958
|
if (!sessionKey.startsWith('sess-')) return { ok: false, error: 'OpenAI Platform 登录态无效,请重新同步' }
|
|
@@ -954,19 +963,23 @@ export class CodexApiQuotaService {
|
|
|
954
963
|
options.signal?.addEventListener('abort', onAbort, { once: true })
|
|
955
964
|
let probe
|
|
956
965
|
try {
|
|
957
|
-
|
|
966
|
+
if (session.balance && typeof session.balance === 'object') {
|
|
967
|
+
probe = await fetchOpenAiCreditBalanceFromBody(session.balance, organizationId)
|
|
968
|
+
} else {
|
|
969
|
+
probe = await fetchOpenAiCreditBalance(sessionKey, organizationId, controller.signal)
|
|
970
|
+
}
|
|
971
|
+
} catch (error) {
|
|
972
|
+
probe = { ok: false, error: scrubSecrets(error instanceof Error ? error.message : String(error)) }
|
|
958
973
|
} finally {
|
|
959
974
|
options.signal?.removeEventListener('abort', onAbort)
|
|
960
975
|
this.controllers.delete(controller)
|
|
961
976
|
}
|
|
962
977
|
if (generation !== this.generation || this.disposed) return { ok: false, error: '同步已被更新或取消,请重试' }
|
|
963
|
-
if (!probe.ok) return { ok: false, error: probe.message }
|
|
978
|
+
if (!probe.ok) return { ok: false, error: probe.message || probe.error || 'OpenAI 余额校验失败,请重试' }
|
|
964
979
|
|
|
965
980
|
const payload = {
|
|
966
981
|
sessionKey,
|
|
967
982
|
organizationId,
|
|
968
|
-
source: 'openai-platform-browser',
|
|
969
|
-
updatedAt: Date.now(),
|
|
970
983
|
}
|
|
971
984
|
try {
|
|
972
985
|
await this.ctx.credentials.modifyRecord(this.key, async () => ({ kind: 'grant', payload }))
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
const spaces = await listTaskSpaces();
|
|
2
|
+
const existing = spaces.find(space => space.name === "codex-credit-openai-session");
|
|
3
|
+
let task;
|
|
4
|
+
if (existing?.ownership === "agentDelegatedToUser") {
|
|
5
|
+
task = await takeOverTaskSpace(existing.id);
|
|
6
|
+
} else if (existing?.ownership === "user") {
|
|
7
|
+
task = await claimTaskSpace(existing.id);
|
|
8
|
+
} else if (existing) {
|
|
9
|
+
task = await taskSpace(existing.id);
|
|
10
|
+
} else {
|
|
11
|
+
task = await taskSpace("codex-credit-openai-session");
|
|
12
|
+
}
|
|
13
|
+
const pages = await task.pages();
|
|
14
|
+
const page = pages[0] ?? await task.adopt((await task.tabs())[0].page);
|
|
15
|
+
let result = { sessionKey: null, organizationId: "", balance: null, error: "", code: "" };
|
|
16
|
+
try {
|
|
17
|
+
const currentUrl = await page.url().catch(() => "");
|
|
18
|
+
// Do not interrupt credentials or 2FA already being entered on the login
|
|
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 () => {
|
|
38
|
+
const request = async (url, options) => {
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const timer = setTimeout(() => controller.abort(), 20000);
|
|
41
|
+
try {
|
|
42
|
+
return await fetch(url, { ...options, signal: controller.signal });
|
|
43
|
+
} finally {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const readJson = async response => {
|
|
48
|
+
const text = await response.text();
|
|
49
|
+
try { return { response, body: JSON.parse(text) }; }
|
|
50
|
+
catch { return { response, body: null }; }
|
|
51
|
+
};
|
|
52
|
+
let accessToken = "";
|
|
53
|
+
try {
|
|
54
|
+
const raw = localStorage.getItem("oai-auth:onboard");
|
|
55
|
+
const auth = raw ? JSON.parse(raw) : null;
|
|
56
|
+
if (typeof auth?.accessToken === "string") accessToken = auth.accessToken;
|
|
57
|
+
} catch {}
|
|
58
|
+
if (!accessToken) return { code: "login-required", error: "请先在已打开的 Ego Lite 页面登录 OpenAI Platform,登录成功后返回插件再次点击同步" };
|
|
59
|
+
|
|
60
|
+
const login = await request("https://api.openai.com/v1/dashboard/onboarding/login", {
|
|
61
|
+
method: "POST",
|
|
62
|
+
headers: { Authorization: "Bearer " + accessToken, "Content-Type": "application/json" },
|
|
63
|
+
body: "{}",
|
|
64
|
+
});
|
|
65
|
+
const loginResult = await readJson(login);
|
|
66
|
+
if (login.status === 401 || login.status === 403) {
|
|
67
|
+
return { code: "login-required", error: "OpenAI Platform 登录已失效,请在已打开的页面重新登录后再次同步" };
|
|
68
|
+
}
|
|
69
|
+
if (!login.ok || !loginResult.body) {
|
|
70
|
+
return { code: "login-exchange-failed", error: "OpenAI 登录态兑换失败(HTTP " + login.status + "),请稍后重试" };
|
|
71
|
+
}
|
|
72
|
+
const sessionKey = loginResult.body?.user?.session?.sensitive_id;
|
|
73
|
+
if (typeof sessionKey !== "string" || !sessionKey.startsWith("sess-")) {
|
|
74
|
+
return { code: "session-missing", error: "OpenAI 登录响应未包含有效会话,请重新同步登录态" };
|
|
75
|
+
}
|
|
76
|
+
const orgs = Array.isArray(loginResult.body?.user?.orgs?.data) ? loginResult.body.user.orgs.data : [];
|
|
77
|
+
const org = orgs.find(item => item.personal) || orgs[0];
|
|
78
|
+
const organizationId = typeof org?.id === "string" ? org.id : "";
|
|
79
|
+
const billing = await request("https://api.openai.com/v1/dashboard/billing/credit_grants", {
|
|
80
|
+
method: "GET",
|
|
81
|
+
headers: {
|
|
82
|
+
Authorization: "Bearer " + sessionKey,
|
|
83
|
+
Accept: "application/json",
|
|
84
|
+
...(organizationId ? { "OpenAI-Organization": organizationId } : {}),
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
const billingResult = await readJson(billing);
|
|
88
|
+
if (!billing.ok || !billingResult.body) {
|
|
89
|
+
return { code: billing.status === 401 || billing.status === 403 ? "login-required" : "billing-failed", error: billing.status === 401 || billing.status === 403 ? "OpenAI 会话已失效,请在打开的页面重新登录后再次同步" : "OpenAI 余额读取失败(HTTP " + billing.status + "),请稍后重试" };
|
|
90
|
+
}
|
|
91
|
+
const body = billingResult.body;
|
|
92
|
+
if (body.total_granted === undefined || body.total_used === undefined) {
|
|
93
|
+
return { code: "billing-shape", error: "OpenAI 余额响应格式已变化,请稍后重试" };
|
|
94
|
+
}
|
|
95
|
+
return { ok: true, sessionKey, organizationId, balance: body };
|
|
96
|
+
});
|
|
97
|
+
Object.assign(result, payload);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
result.code = "browser-network";
|
|
100
|
+
result.error = error?.name === "AbortError"
|
|
101
|
+
? "OpenAI 页面网络请求超时(20 秒),请检查 Ego Lite 的网络或代理后重试"
|
|
102
|
+
: String(error?.message || error);
|
|
103
|
+
}
|
|
104
|
+
// A verified balance closes the page. Missing login keeps the page visible and
|
|
105
|
+
// hands control to the user, who can log in and explicitly retry this sync.
|
|
106
|
+
if (result.ok) {
|
|
107
|
+
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.
|
|
111
|
+
let handedOff = false;
|
|
112
|
+
try {
|
|
113
|
+
await page.goto("https://auth.openai.com/log-in", { timeout: 30000 });
|
|
114
|
+
const loginUrl = await page.url();
|
|
115
|
+
if (!loginUrl.startsWith("https://auth.openai.com/")) throw new Error("login page unavailable");
|
|
116
|
+
await task.handOff();
|
|
117
|
+
handedOff = true;
|
|
118
|
+
result.needsLogin = true;
|
|
119
|
+
result.taskSpaceId = task.spaceId;
|
|
120
|
+
} catch {}
|
|
121
|
+
if (!handedOff) {
|
|
122
|
+
result.code = "handoff-failed";
|
|
123
|
+
result.needsLogin = false;
|
|
124
|
+
result.error = "无法打开 OpenAI 登录页,请在 Ego Lite 手动登录 platform.openai.com 后重试";
|
|
125
|
+
await task.finish({ keep: [] }).catch(() => {});
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
await task.finish({ keep: [] }).catch(() => {});
|
|
129
|
+
}
|
|
130
|
+
console.log("__CODEX_OPENAI_SYNC__" + JSON.stringify(result));
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
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.1.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "index.js",
|
|
8
8
|
"engines": {
|
|
@@ -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",
|