-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
4488 lines (4224 loc) · 167 KB
/
Copy pathapp.js
File metadata and controls
4488 lines (4224 loc) · 167 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const localStoreKey = "codex-local-store-v5";
const previousStoreKey = "codex-local-store-v4";
const legacyStoreKey = "codex-account-switcher-store-v3";
const deviceKeyStorage = "codex-dock-device-key-v1";
const previousDeviceKeyStorage = "codex-plus-device-key-v1";
const cachedEmailStorage = "codex-dock-email-v1";
const previousCachedEmailStorage = "codex-cloud-console-email-v1";
const chatgptLoginUrl = "https://chatgpt.com/auth/login";
const chatgptSessionUrl = "https://chatgpt.com/api/auth/session";
const codexLoginCommand = "codex login";
const oauthClientId = "app_EMoamEEZ73f0CkXaXp7hrann";
const oauthRedirectUri = "http://localhost:1455/auth/callback";
const oauthPkceStorage = "codex-dock-oauth-pkce-v1";
const oauthPkceHistoryStorage = "codex-dock-oauth-pkce-history-v1";
const oauthFlowStorage = "codex-dock-oauth-flow-v1";
const oauthFlowDurationMs = 3 * 60 * 1000;
const usageFreshWindowMs = 30 * 60 * 1000;
const backgroundUsageRefreshIntervalMs = 5 * 60 * 1000;
const backgroundUsageRefreshBatchSize = 2;
const { auditTitle, auditDescription } = window.CodexAuditCore;
const {
escapeHtml,
shortId,
formatTime,
formatRefreshTime,
formatResetTime,
planLabel,
planClass,
formatTokenTime,
formatBytes,
errorSeverity,
} = window.CodexFormatCore;
if (!window.CodexSettingsUi) {
throw new Error("CodexSettingsUi 未加载,请检查 settings-ui.js。");
}
const settingsUi = window.CodexSettingsUi.createSettingsUi({ escapeHtml });
if (!window.CodexAccountListUi) {
throw new Error("CodexAccountListUi 未加载,请检查 account-list-ui.js。");
}
if (!window.CodexAccountDetailUi) {
throw new Error("CodexAccountDetailUi 未加载,请检查 account-detail-ui.js。");
}
if (!window.CodexAdminUi) {
throw new Error("CodexAdminUi 未加载,请检查 admin-ui.js。");
}
if (!window.CodexPanelsUi) {
throw new Error("CodexPanelsUi 未加载,请检查 panels-ui.js。");
}
if (!window.CodexProgressUi) {
throw new Error("CodexProgressUi 未加载,请检查 progress-ui.js。");
}
if (!window.CodexShellUi) {
throw new Error("CodexShellUi 未加载,请检查 shell-ui.js。");
}
if (!window.CodexDialogUi) {
throw new Error("CodexDialogUi 未加载,请检查 dialog-ui.js。");
}
if (!window.CodexOauthCore) {
throw new Error("CodexOauthCore 未加载,请检查 oauth-core.js。");
}
const oauthCore = window.CodexOauthCore;
const defaultAccountFilters = {
plan: "all",
token: "all",
usage: "all",
status: "all",
};
const defaultSmartSwitchSettings = {
paidOnly: true,
preferRt: true,
allowAt: false,
showExperimentalAt: false,
avoidCurrent: true,
avoidLow5h: true,
avoidLow7d: true,
cooldownMinutes: 0,
};
const defaultAutoSwitchSettings = {
enabled: false,
fiveHourThreshold: 5,
oneWeekThreshold: 5,
pollSeconds: 15,
idlePollSeconds: 300,
paidOnly: true,
preferRt: true,
allowAt: false,
showExperimentalAt: false,
avoidCurrent: true,
avoidLow5h: true,
avoidLow7d: true,
cooldownMinutes: 10,
globalCooldownSeconds: 180,
onlyWhenIdle: true,
idleSeconds: 10,
activityQuietSeconds: 120,
cpuQuietSeconds: 90,
cpuBusyPercent: 3,
};
const defaultUsageRefreshSettings = {
usageRefreshMode: "helper",
cloudUsageRefreshEnabled: false,
helperFallbackToCloud: false,
usageRefreshConcurrency: 1,
usageRefreshIntervalMs: 1500,
lastUsageRefreshSource: "",
lastUsageRefreshAt: "",
};
const minimumHelperVersion = "0.4.2";
const state = {
user: null,
authResolved: false,
localAccounts: [],
cloudAccounts: [],
accounts: [],
audit: [],
adminSummary: null,
adminUsers: [],
adminAudit: [],
adminDevices: [],
selectedAdminUserIds: new Set(),
adminFilters: {
userQuery: "",
role: "",
status: "",
auditQuery: "",
auditAction: "",
},
selectedId: null,
accountFilter: "all",
accountHealthFilter: "all",
accountFilters: { ...defaultAccountFilters },
accountSort: "updated",
accountLayout: "list",
selectedBulkIds: new Set(),
cleanupPendingIds: [],
smartSwitchSettings: { ...defaultSmartSwitchSettings },
autoSwitchSettings: { ...defaultAutoSwitchSettings },
usageRefreshSettings: { ...defaultUsageRefreshSettings },
autoSwitchStatus: {
helperAuthorized: false,
lastCheck: "",
lastSwitch: "",
lastReason: "",
},
accountSearch: "",
sidebarCollapsed: localStorage.getItem("codex-sidebar-collapsed-v1") === "1",
currentView: "accounts",
settingsTab: "account",
helperReady: false,
helperBase: "",
helperInfo: null,
helperRelease: null,
codexProxy: null,
codexStatus: null,
deviceKey: "",
localAuthFingerprint: "",
currentAuthKey: "",
currentAuthAccount: null,
currentAuthChecking: false,
autoImportingLocalAuth: false,
refreshingUsage: false,
backgroundUsageRefreshRunning: false,
lastBackgroundUsageRefreshAt: "",
lastBackgroundUsageRefreshSummary: "",
pendingImportItems: [],
commandFiles: [],
importMode: "oauth",
importCompleted: false,
operationProgress: {
active: false,
done: false,
title: "",
summary: "",
items: [],
},
pendingManualSwitch: null,
authMode: "login",
syncChoices: {},
oauthAuthUrl: "",
oauthCodeVerifier: "",
oauthState: "",
oauthCallbackPoll: null,
lastOauthCallbackUrl: "",
oauthFlowTimer: null,
oauthFlow: {
active: false,
phase: "idle",
state: "",
authUrl: "",
startedAt: 0,
expiresAt: 0,
error: "",
summary: "",
},
};
const $ = (id) => document.getElementById(id);
if (!window.CodexAccountCore) {
throw new Error("CodexAccountCore 未加载,请检查 account-core.js。");
}
const {
decodeJwtPayload,
bestPlan,
explainError,
normalizeUsage,
newestUsage,
parseImportEntries,
parseSession,
authFingerprint,
accountDedupeKey,
hasUsableRefreshToken,
accessTokenExpiry,
accountPlan,
normalizeLocalAccount,
normalizeCloudAccount,
} = window.CodexAccountCore;
if (!window.CodexImportCore) {
throw new Error("CodexImportCore 未加载,请检查 import-core.js。");
}
const {
importStatusClass,
importIdentityKeys,
buildPendingImportItems: buildPendingImportItemsCore,
normalizePendingImportStatuses: normalizePendingImportStatusesCore,
summarizeImportPreview,
accountToImportPayload,
findImportedAccounts,
previewImportEntries,
hasUsageSnapshot,
} = window.CodexImportCore.createImportCore({
accountCore: window.CodexAccountCore,
formatCore: window.CodexFormatCore,
tokenState,
});
if (!window.CodexImportUi) {
throw new Error("CodexImportUi 未加载,请检查 import-ui.js。");
}
if (!window.CodexPlatformClients) {
throw new Error("CodexPlatformClients 未加载,请检查 platform-clients.js。");
}
const {
createCloudApiClient,
createHelperClient,
helperBaseCandidates,
isKnownHelperHealth,
} = window.CodexPlatformClients;
const cloudApi = createCloudApiClient();
const api = (path, options = {}) => cloudApi.request(path, options);
const accountListUi = window.CodexAccountListUi.createAccountListUi({
formatCore: window.CodexFormatCore,
escapeHtml,
shortId,
formatRefreshTime,
planLabel,
planClass,
errorSeverity,
explainError,
accountPlan,
tokenState,
usageIssue,
accountActionMode,
sourceLabel,
});
const accountDetailUi = window.CodexAccountDetailUi.createAccountDetailUi({
formatCore: window.CodexFormatCore,
escapeHtml,
shortId,
formatTime,
formatResetTime,
planLabel,
planClass,
errorSeverity,
explainError,
accountPlan,
tokenState,
usageIssue,
canUseAccount,
sourceLabel,
});
const adminUi = window.CodexAdminUi.createAdminUi({
formatCore: window.CodexFormatCore,
auditCore: window.CodexAuditCore,
escapeHtml,
shortId,
formatTime,
auditTitle,
auditDescription,
});
const panelsUi = window.CodexPanelsUi.createPanelsUi({
formatCore: window.CodexFormatCore,
auditCore: window.CodexAuditCore,
escapeHtml,
formatBytes,
formatTime,
auditTitle,
auditDescription,
});
const progressUi = window.CodexProgressUi.createProgressUi({
escapeHtml,
});
const shellUi = window.CodexShellUi.createShellUi({
formatCore: window.CodexFormatCore,
escapeHtml,
formatBytes,
cloudBackupEnabled,
canUseAccount,
resolveCurrentAccountId,
accountPlan,
tokenState,
});
const dialogUi = window.CodexDialogUi.createDialogUi({
escapeHtml,
});
const importUi = window.CodexImportUi.createImportUi({
formatCore: window.CodexFormatCore,
escapeHtml,
shortId,
importStatusClass,
summarizeImportPreview,
});
function helperClient() {
return createHelperClient(state.helperBase);
}
function normalizeHelperRelease(manifest = {}) {
const helper = manifest.helper || {};
if (!helper.file && !helper.sha256 && !helper.version) return null;
const helperPackage = helper.package || {};
return {
...helper,
version: helper.version || minimumHelperVersion,
build_date: helper.build_date || helper.buildDate || "",
assetVersion: manifest.version || "",
downloadUrl: helper.file ? `/${String(helper.file).replace(/^\/+/, "")}` : "/downloads/CodexDockHelper.exe",
package: {
...helperPackage,
downloadUrl: helperPackage.file ? `/${String(helperPackage.file).replace(/^\/+/, "")}` : "",
},
};
}
async function loadHelperRelease() {
try {
const response = await fetch(`/asset-manifest.json?ts=${Date.now()}`, { cache: "no-store" });
if (!response.ok) throw new Error(`manifest ${response.status}`);
state.helperRelease = normalizeHelperRelease(await response.json());
} catch {
state.helperRelease = {
version: minimumHelperVersion,
build_date: "",
downloadUrl: "/downloads/CodexDockHelper.exe",
};
}
renderDevice();
renderSettings();
}
function helperAuthorizedForCurrentConsole(helper = state.helperInfo) {
const autoSwitch = helper?.auto_switch || helper?.autoSwitch || {};
if (!autoSwitch.authorized || !autoSwitch.cloud_base) return false;
try {
return new URL(autoSwitch.cloud_base).origin === window.location.origin;
} catch {
return false;
}
}
function toast(message) {
const el = $("toast");
el.textContent = message;
el.hidden = false;
window.clearTimeout(toast.timer);
toast.timer = window.setTimeout(() => {
el.hidden = true;
}, 2600);
}
function showImportResult(result) {
const el = $("importResult");
if (!el) return;
el.hidden = false;
el.innerHTML = importUi.renderImportResult(result);
renderImportPreview();
}
function formatCountdown(ms) {
const totalSeconds = Math.max(0, Math.ceil(ms / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}
function oauthFlowView(flow = state.oauthFlow) {
const now = Date.now();
const remaining = Math.max(0, Number(flow.expiresAt || 0) - now);
const elapsed = Math.max(0, now - Number(flow.startedAt || now));
const total = Math.max(1, Number(flow.expiresAt || 0) - Number(flow.startedAt || 0));
const waitProgress = Math.min(42, Math.max(4, Math.round((elapsed / total) * 42)));
const phase = flow.phase || "idle";
const views = {
opening: {
iconClass: "busy",
title: "正在打开授权页面",
detail: "请在新打开的浏览器页面完成登录授权。",
hint: "本页正在监听授权回调。",
busy: true,
progress: 8,
showCountdown: true,
showCancel: true,
showRetry: false,
showDone: false,
},
waiting: {
iconClass: "busy",
title: "等待授权中",
detail: "请在新打开的浏览器页面完成登录。授权完成后,本页会自动接收回调。",
hint: "完成后会自动换取 RT 并导入账号。",
busy: true,
progress: waitProgress,
showCountdown: true,
showCancel: true,
showRetry: true,
showDone: false,
},
received: {
iconClass: "busy",
title: "已收到授权回调",
detail: "正在校验授权结果。",
hint: "请保持本页打开。",
busy: true,
progress: 55,
showCountdown: true,
showCancel: false,
showRetry: false,
showDone: false,
},
exchanging: {
iconClass: "busy",
title: "正在换取 RT",
detail: "已收到 OAuth code,正在换取可用于 Codex 的 refresh token。",
hint: "这一步通常只需要几秒。",
busy: true,
progress: 72,
showCountdown: false,
showCancel: false,
showRetry: false,
showDone: false,
},
importing: {
iconClass: "busy",
title: "正在导入账号",
detail: "RT 已获取,正在写入账号池并同步云端。",
hint: "导入完成后会自动刷新账号状态。",
busy: true,
progress: 90,
showCountdown: false,
showCancel: false,
showRetry: false,
showDone: false,
},
success: {
iconClass: "success",
title: "导入成功",
detail: flow.summary || "账号已导入账号池,可用于 Codex。",
hint: "可以继续导入其它账号,或关闭导入窗口。",
busy: false,
progress: 100,
showCountdown: false,
showCancel: false,
showRetry: false,
showDone: true,
},
expired: {
iconClass: "warning",
title: "授权等待已过期",
detail: "本次授权监听已超过有效时间。旧回调可能无法再使用,请重新打开授权页面。",
hint: "倒计时按真实时间计算,页面后台或系统卡顿不会延长有效期。",
busy: false,
progress: 100,
showCountdown: false,
showCancel: true,
showRetry: true,
showDone: false,
},
error: {
iconClass: "error",
title: "导入失败",
detail: flow.error || "授权或导入过程中出现错误。",
hint: "请重新打开授权页面,不要复用旧回调。",
busy: false,
progress: 100,
showCountdown: false,
showCancel: true,
showRetry: true,
showDone: false,
},
};
return { remaining, ...(views[phase] || views.waiting) };
}
function renderOauthFlow() {
const overlay = $("oauthFlowOverlay");
if (!overlay) return;
const flow = state.oauthFlow || {};
overlay.hidden = !flow.active;
if (!flow.active) return;
const view = oauthFlowView(flow);
$("oauthFlowIcon").textContent = "";
$("oauthFlowIcon").className = `oauth-flow-icon ${view.iconClass || ""}`.trim();
$("oauthFlowTitle").textContent = view.title;
$("oauthFlowDetail").textContent = view.detail;
$("oauthFlowCountdown").textContent = view.showCountdown ? `剩余 ${formatCountdown(view.remaining)}` : "";
$("oauthFlowHint").textContent = view.hint;
$("oauthFlowMeter").style.width = `${view.progress}%`;
$("oauthFlowCancelBtn").hidden = !view.showCancel;
$("oauthFlowRetryBtn").hidden = !view.showRetry;
$("oauthFlowDoneBtn").hidden = !view.showDone;
}
function stopOauthFlowTimer() {
if (state.oauthFlowTimer) {
clearInterval(state.oauthFlowTimer);
state.oauthFlowTimer = null;
}
}
function setOauthFlow(patch = {}) {
state.oauthFlow = { ...state.oauthFlow, ...patch };
renderOauthFlow();
persistOauthFlow();
const phase = state.oauthFlow.phase;
if (!state.oauthFlow.active || ["success", "error", "expired"].includes(phase)) stopOauthFlowTimer();
}
function startOauthFlowTimer() {
stopOauthFlowTimer();
state.oauthFlowTimer = setInterval(() => {
const flow = state.oauthFlow;
if (!flow.active) {
stopOauthFlowTimer();
return;
}
if (["opening", "waiting"].includes(flow.phase) && Date.now() >= Number(flow.expiresAt || 0)) {
stopOauthCallbackPolling();
setOauthFlow({ phase: "expired" });
return;
}
renderOauthFlow();
}, 1000);
renderOauthFlow();
}
function cancelOauthFlow(options = {}) {
stopOauthCallbackPolling();
stopOauthFlowTimer();
state.oauthFlow = {
active: false,
phase: "idle",
state: "",
authUrl: "",
startedAt: 0,
expiresAt: 0,
error: "",
summary: "",
};
localStorage.removeItem(oauthFlowStorage);
renderOauthFlow();
if (!options.silent) toast("已取消 OAuth 导入。");
}
function persistOauthFlow(flow = state.oauthFlow) {
const status = oauthCore.oauthFlowSnapshotStatus(flow, Date.now());
if (status.ok) {
localStorage.setItem(oauthFlowStorage, JSON.stringify(status.flow));
} else {
localStorage.removeItem(oauthFlowStorage);
}
}
function restoreOauthFlow() {
const status = oauthCore.oauthFlowSnapshotStatus(localStorage.getItem(oauthFlowStorage), Date.now());
if (!status.ok) {
localStorage.removeItem(oauthFlowStorage);
return false;
}
const pkce = oauthPkce(status.flow.state);
if (!pkce?.verifier) {
localStorage.removeItem(oauthFlowStorage);
return false;
}
state.oauthCodeVerifier = pkce.verifier;
state.oauthState = status.flow.state;
state.oauthAuthUrl = status.flow.authUrl || pkce.authUrl || "";
state.oauthFlow = { ...state.oauthFlow, ...status.flow, phase: "waiting" };
if ($("oauthAuthUrl")) $("oauthAuthUrl").value = state.oauthAuthUrl;
setDrawer(true, { mode: "oauth" });
startOauthFlowTimer();
startOauthCallbackPolling();
toast("已恢复未完成的 OAuth 导入,本页继续等待回调。");
return true;
}
function randomBase64Url(byteLength = 32) {
const bytes = new Uint8Array(byteLength);
crypto.getRandomValues(bytes);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
async function sha256Base64Url(value) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
let binary = "";
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function isFreshOauthPkce(payload) {
return Boolean(payload?.verifier && payload?.state && Date.now() - Number(payload.createdAt || 0) < 30 * 60 * 1000);
}
function readOauthPkceHistory() {
const history = {};
try {
const parsed = JSON.parse(localStorage.getItem(oauthPkceHistoryStorage) || "{}");
for (const [key, payload] of Object.entries(parsed || {})) {
if (isFreshOauthPkce(payload)) history[key] = payload;
}
} catch {
// Ignore broken cache; a fresh authorization link will rebuild it.
}
try {
const current = JSON.parse(localStorage.getItem(oauthPkceStorage) || "{}");
if (isFreshOauthPkce(current)) history[current.state] = current;
} catch {
// Ignore legacy cache parse errors.
}
return history;
}
function writeOauthPkceHistory(history) {
const fresh = Object.values(history || {})
.filter(isFreshOauthPkce)
.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0))
.slice(0, 12)
.reduce((acc, payload) => {
acc[payload.state] = payload;
return acc;
}, {});
localStorage.setItem(oauthPkceHistoryStorage, JSON.stringify(fresh));
}
function rememberOauthPkce(verifier, stateValue, authUrl = state.oauthAuthUrl || "") {
const payload = { verifier, state: stateValue, redirectUri: oauthRedirectUri, clientId: oauthClientId, createdAt: Date.now(), authUrl };
state.oauthCodeVerifier = verifier;
state.oauthState = stateValue;
localStorage.setItem(oauthPkceStorage, JSON.stringify(payload));
const history = readOauthPkceHistory();
history[stateValue] = payload;
writeOauthPkceHistory(history);
}
function oauthPkce(stateValue = "") {
if (stateValue) return readOauthPkceHistory()[stateValue] || {};
try {
const payload = JSON.parse(localStorage.getItem(oauthPkceStorage) || "{}");
if (isFreshOauthPkce(payload)) return payload;
} catch {
return {};
}
return {};
}
function forgetOauthPkce(stateValue) {
if (!stateValue) return;
const current = oauthPkce();
if (current.state === stateValue) localStorage.removeItem(oauthPkceStorage);
const history = readOauthPkceHistory();
delete history[stateValue];
writeOauthPkceHistory(history);
}
async function refreshOauthAuthorizeUrl(options = {}) {
const reuse = options.reuse !== false;
const existing = reuse ? oauthPkce() : {};
if (existing?.verifier && existing?.state && existing?.authUrl) {
state.oauthCodeVerifier = existing.verifier;
state.oauthState = existing.state;
state.oauthAuthUrl = existing.authUrl;
if ($("oauthAuthUrl")) $("oauthAuthUrl").value = state.oauthAuthUrl;
return state.oauthAuthUrl;
}
const verifier = randomBase64Url(64);
const stateValue = randomBase64Url(18);
const challenge = await sha256Base64Url(verifier);
const params = new URLSearchParams({
response_type: "code",
client_id: oauthClientId,
redirect_uri: oauthRedirectUri,
scope: "openid email profile offline_access",
audience: "https://api.openai.com/v1",
code_challenge: challenge,
code_challenge_method: "S256",
state: stateValue,
});
state.oauthAuthUrl = `https://auth.openai.com/oauth/authorize?${params.toString()}`;
rememberOauthPkce(verifier, stateValue, state.oauthAuthUrl);
if ($("oauthAuthUrl")) $("oauthAuthUrl").value = state.oauthAuthUrl;
return state.oauthAuthUrl;
}
async function resetOauthAuthorizeUrl() {
localStorage.removeItem(oauthPkceStorage);
state.oauthAuthUrl = "";
state.oauthCodeVerifier = "";
state.oauthState = "";
return refreshOauthAuthorizeUrl({ reuse: false });
}
async function currentOauthAuthorizeUrl(options = {}) {
if (options.fresh) return refreshOauthAuthorizeUrl({ reuse: false });
const current = oauthPkce();
if (state.oauthAuthUrl && current.authUrl === state.oauthAuthUrl) return state.oauthAuthUrl;
return refreshOauthAuthorizeUrl();
}
async function beginOauthAuthorization(options = {}) {
setImportMode("oauth");
const authUrl = await currentOauthAuthorizeUrl({ fresh: true });
const pkce = oauthPkce();
const now = Date.now();
setOauthFlow({
active: true,
phase: options.copyOnly ? "waiting" : "opening",
state: pkce.state || state.oauthState || "",
authUrl,
startedAt: now,
expiresAt: now + oauthFlowDurationMs,
error: "",
summary: "",
});
startOauthFlowTimer();
startOauthCallbackPolling();
if (options.copyOnly) {
await navigator.clipboard.writeText(authUrl);
toast("授权链接已复制,本页正在等待回调。");
return;
}
const popup = window.open(authUrl, "_blank");
if (!popup) {
setOauthFlow({
phase: "error",
error: "浏览器拦截了授权页面弹窗。请允许弹窗后重新打开授权页面,或复制授权链接手动打开。",
});
return;
}
setOauthFlow({ phase: "waiting" });
toast(state.helperReady ? "授权页面已打开,本页正在等待回调。" : "授权页面已打开;Agent 未连接时可能需要手动粘贴回调。");
}
async function handleAuthAcquireAction(action) {
if (action === "open-import-oauth-login") {
closeModal("accountDetailModal");
setDrawer(true, { mode: "oauth" });
await beginOauthAuthorization();
return;
}
if (action === "open-import-session" || action === "open-import-oauth" || action === "open-import-file") {
closeModal("accountDetailModal");
setDrawer(true, { mode: action === "open-import-file" ? "file" : (action === "open-import-oauth" ? "oauth" : "session") });
toast(action === "open-import-file" ? "请导入该账号自己的 auth.json。" : (action === "open-import-oauth" ? "已打开 OAuth 导入。" : "已打开 Session 导入。"));
return;
}
if (action === "open-chatgpt-login") {
window.open(chatgptLoginUrl, "_blank", "noopener,noreferrer");
return;
}
if (action === "open-session-json") {
window.open(chatgptSessionUrl, "_blank", "noopener,noreferrer");
toast("登录后复制页面 JSON,再回到导入页粘贴解析。");
return;
}
if (action === "copy-session-url") {
await navigator.clipboard.writeText(chatgptSessionUrl);
toast("Session 地址已复制。");
return;
}
if (action === "copy-codex-login") {
await navigator.clipboard.writeText(codexLoginCommand);
toast("Codex 登录命令已复制。它会改变当前 Codex 登录态,只用于登录你要导入的目标账号。");
return;
}
if (action === "open-oauth-login") {
await beginOauthAuthorization();
return;
}
if (action === "copy-oauth-url") {
await beginOauthAuthorization({ copyOnly: true });
return;
}
if (action === "sync-local-auth") {
await importCurrentLocalAuth();
}
}
function buildPendingImportItems(entries, sourceName) {
return buildPendingImportItemsCore(entries, sourceName, {
existingAccounts: state.user ? state.cloudAccounts : state.localAccounts,
});
}
function normalizePendingImportStatuses(items) {
return normalizePendingImportStatusesCore(items, {
existingAccounts: state.user ? state.cloudAccounts : state.localAccounts,
});
}
function renderImportPreview() {
const list = $("importPreviewList");
const summary = $("importPreviewSummary");
const confirm = $("confirmImportBtn");
if (!list || !summary || !confirm) return;
const rendered = importUi.renderImportPreview(state.pendingImportItems, {
importCompleted: state.importCompleted,
operationActive: state.operationProgress.active,
});
const finish = $("finishImportBtn");
const clear = $("clearFormBtn");
confirm.hidden = rendered.confirmHidden;
confirm.disabled = rendered.confirmDisabled;
finish.hidden = rendered.finishHidden;
finish.classList.toggle("primary", rendered.finishPrimary);
clear.textContent = rendered.clearText;
clear.classList.toggle("soft-action", rendered.clearSoft);
summary.textContent = rendered.summaryText;
list.innerHTML = rendered.listHtml;
}
function setImportMode(mode) {
state.importMode = mode;
document.querySelectorAll("[data-import-mode]").forEach((button) => {
button.classList.toggle("active", importUi.modeIsActive(mode, button.dataset.importMode));
});
document.querySelectorAll("[data-import-panel]").forEach((panel) => {
panel.classList.toggle("active", importUi.modeIsActive(mode, panel.dataset.importPanel));
});
const advancedPanel = document.querySelector(".advanced-import-panel");
if (advancedPanel) advancedPanel.open = mode !== "oauth";
if (mode === "oauth") refreshOauthAuthorizeUrl().catch(() => toast("OAuth 授权链接生成失败。"));
}
function clearImportWorkflow() {
cancelOauthFlow({ silent: true });
state.pendingImportItems = [];
state.importCompleted = false;
$("sessionInput").value = "";
if ($("oauthCallbackInput")) $("oauthCallbackInput").value = "";
$("jsonFileInput").value = "";
$("importResult").hidden = true;
renderImportPreview();
}
function importableJsonFiles(fileList) {
return Array.from(fileList || []).filter((file) => /\.json$/i.test(file.name) || file.type === "application/json" || !file.type);
}
function setCommandFiles(fileList) {
const next = importableJsonFiles(fileList);
const byKey = new Map(state.commandFiles.map((file) => [`${file.name}:${file.size}:${file.lastModified}`, file]));
for (const file of next) byKey.set(`${file.name}:${file.size}:${file.lastModified}`, file);
state.commandFiles = [...byKey.values()];
renderCommandAttachments();
renderShellState();
if (!next.length && fileList?.length) toast("这里只支持 JSON 文件。");
}
function clearCommandFiles() {
state.commandFiles = [];
renderCommandAttachments();
renderShellState();
}
function renderCommandAttachments() {
const list = $("commandAttachments");
if (!list) return;
list.hidden = !state.commandFiles.length;
list.innerHTML = shellUi.renderCommandAttachments(state.commandFiles);
}
function renderShellState() {
const button = $("quickSwitchBtn");
const shell = $("commandShell");
if (!button || !shell) return;
const view = shellUi.commandShellState({
files: state.commandFiles,
accounts: state.accounts,
});
button.textContent = view.quickSwitchText;
button.disabled = view.quickSwitchDisabled;
shell.classList.toggle("has-attachments", view.hasFiles);
}
function renderToolbarState(filtered = visibleAccounts()) {
const sort = $("accountSortSelect");
if (sort) sort.value = state.accountSort;
const filters = state.accountFilters || defaultAccountFilters;
const map = { filterPlan: "plan", filterToken: "token", filterUsage: "usage", filterStatus: "status" };
for (const [id, key] of Object.entries(map)) {
if ($(id)) $(id).value = filters[key] || "all";
}
document.querySelectorAll("[data-filter]").forEach((button) => button.classList.toggle("active", button.dataset.filter === state.accountFilter));
document.querySelectorAll("[data-layout]").forEach((button) => button.classList.toggle("active", button.dataset.layout === state.accountLayout));
const view = shellUi.toolbarState({
filtered,
selectedBulkIds: state.selectedBulkIds,
helperReady: state.helperReady,
canRefreshUsage: canRefreshAccountUsage,
isInvalidAccount,
});
$("bulkCount").textContent = view.bulkText;
$("bulkBar").classList.toggle("has-selection", view.hasSelection);
$("bulkRefreshBtn").disabled = view.refreshDisabled;
$("bulkExportBtn").disabled = view.exportDisabled;
$("bulkDeleteBtn").disabled = view.deleteDisabled;
$("bulkDeleteBtn").textContent = view.deleteText;
$("bulkCleanupHint").textContent = view.cleanupHint;
$("bulkPrioritySelect").disabled = view.priorityDisabled;
}
function parseImportTextToPreview() {
const text = $("sessionInput").value.trim();
if (!text) {
state.pendingImportItems = [];
state.importCompleted = false;
showImportResult({ preview: true, message: "先粘贴账号 JSON,再解析。" });
renderImportPreview();
return;
}
try {
state.pendingImportItems = normalizePendingImportStatuses(buildPendingImportItems(parseImportEntries(text), "粘贴文本"));
state.importCompleted = false;
$("importResult").hidden = true;
renderImportPreview();
} catch (error) {
state.pendingImportItems = [{
id: crypto.randomUUID(),
ok: false,
status: "无法解析",
sourceName: "粘贴文本",
accountName: "JSON",
error: error.message || "JSON 格式不正确",
}];
state.importCompleted = false;
renderImportPreview();
}
}
function normalizeOauthCallbackValue(raw) {
return oauthCore.normalizeOauthCallbackValue(raw, oauthRedirectUri);
}
function callbackParams(raw) {
return oauthCore.callbackParams(raw, oauthRedirectUri);
}
async function exchangeOauthCode(code, pkce) {
const result = await api("/api/oauth/exchange", {
method: "POST",
body: {
code,
codeVerifier: pkce.verifier,
redirectUri: pkce.redirectUri || oauthRedirectUri,
clientId: pkce.clientId || oauthClientId,
},
});
return result.token || result;
}
async function parseOauthCallbackToPreview(rawCallback = null) {
try {
const callbackSource = typeof rawCallback === "string" ? rawCallback : $("oauthCallbackInput").value;
const params = callbackParams(callbackSource);
let accessToken = params.get("access_token") || params.get("accessToken") || "";
let idToken = params.get("id_token") || params.get("idToken") || "";
let refreshToken = params.get("refresh_token") || params.get("refreshToken") || "";
const code = params.get("code") || "";
const returnedState = params.get("state") || "";
if (state.oauthFlow.active) {
const stateStatus = oauthCore.callbackStateStatus(params, state.oauthFlow.state || state.oauthState || "", oauthRedirectUri);
if (!stateStatus.ok) throw new Error(stateStatus.message);
}
const providerError = oauthCore.providerErrorStatus(params, oauthRedirectUri);
if (!providerError.ok) throw new Error(providerError.message);
let usedOauthCode = false;