Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
5321 lines (4927 loc) · 205 KB
/
Copy pathmain.js
File metadata and controls
5321 lines (4927 loc) · 205 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 {
app,
BrowserWindow,
Menu,
Tray,
ipcMain,
nativeImage,
safeStorage,
screen,
shell,
session: electronSession,
dialog,
} = require("electron");
const crypto = require("node:crypto");
const fs = require("node:fs/promises");
const fsSync = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const readline = require("node:readline");
const { spawn } = require("node:child_process");
const { fileCredentialStoreConfig, resolveCodexHome } = require("./codex-config");
const { WINDOWS_DESKTOP_SCAN, WINDOWS_WRITERS_SCAN, WINDOWS_CONFLICT_OUTPUT,
parseProcessRecords, canStopConflicts, stopConflictsScript } = require("./codex-process-guard");
const { normalizeSubscription, subscriptionFromClaims } = require("./subscription");
const {
QUOTA_CONFLICT_WINDOW_MS,
QUOTA_ESTIMATE_ALGORITHM,
QUOTA_MODE_LOCAL,
QUOTA_MODE_ONLINE,
TOKEN_LEDGER_VERSION,
TOKEN_LEDGER_SCAN_LIMIT,
TOKEN_LEDGER_FILE_LIMIT,
TOKEN_LEDGER_EVENT_LIMIT,
SESSION_POLL_RECENT_FILE_LIMIT,
SESSION_POLL_RECENT_WINDOW_MS,
} = require("./quota/constants");
const {
emptyTokenUsage,
normalizeTokenUsage,
addTokenUsage,
subtractTokenUsage,
tokenUsageTotal,
codexRateCard,
quotaSpeedMultiplier,
weightedTokenUsage,
cloneTokenUsage,
dateMs,
median,
normalizePlanType,
fallbackQuotaCoefficient,
quotaCoefficientBounds,
isReasonableQuotaCoefficient,
} = require("./quota/token-math");
const { scopedTokenDelta } = require("./quota/usage-math");
const { createRecordCache, aggregateUsage, quotaFromRecords, normalizeBucket, combineBuckets, windowFor, normalizeResetCredits, numberOrNull } = require("./quota/local-records");
const { estimateLocalQuota } = require("./quota/local-estimate");
const { observeOfficialQuota, estimateOfficialQuota, OFFICIAL_SOURCES } = require("./quota/official-estimate");
const { readBrowserResetCredits } = require("./quota/browser-reset-cache");
const { recoverAccountIndex } = require("./account-recovery");
const { encryptPortableCredentials, decryptPortableCredentials, validatePassword, MAX_BUNDLE_BYTES } = require("./portable-credentials");
const { createUpdateChecker } = require("./github-updates");
const { createMessageDialogs } = require("./message-dialog");
const { translate, normalizeLanguage } = require("./ui/i18n");
const t = (source, ...values) => translate(runtimeSettings?.language, source, ...values);
const { createAutoRecovery, POLL_MS } = require("./auto-recovery");
const { createGoalBridge } = require("./codex-goals");
const { createAccountLogin, cleanupLoginHomes } = require("./account-login");
let accountLogin = null;
let loginQuitPending = false;
const { createRecoveryCountdown, normalizeCountdownPosition, countdownBounds } = require("./recovery-countdown");
const { createDesktopBridge, readLocalThreadAnchor, readLocalThreadMetadata } = require("./codex-desktop-bridge");
const { createDesktopQuotaReader, quotaFromDesktopUsage } = require("./quota/desktop-quota");
const { createOnlineAccounts, SOURCE: ONLINE_ACCOUNT_SOURCE } = require("./quota/online-accounts");
let onlineAccounts = null;
let onlineQuitReady = false;
let autoRecovery = null;
let autoRecoveryTimer = null;
let recoveryCountdown = null;
let recoveryCountdownWindow = null;
let updateChecker = null;
let updateDialogPending = false;
let messageDialogs = null;
const readRecordFile = createRecordCache();
let detectedCodexVersion = null;
let selectedLogsDb = null;
let selectedLogsDbAt = 0;
const { createLocalDataCache } = require("./quota/local-data-cache");
const {
MAC_CODEX_APP_NAMES,
credentialFileExtension,
credentialProtectionLabel,
isEncryptedCredentialBackup,
platformDisplayName,
} = require("./platform-support");
const APP_NAME = "CodexAuth Switch";
const APP_ID = "local.codexauth.switch";
const STARTUP_ARG = "--codexauth-startup";
const STORE_DIR_NAME = "codex-auth-switcher";
const STORE_VERSION = 1;
const isWindows = process.platform === "win32";
const isMac = process.platform === "darwin";
const WIDGET_WIDTH = 340;
const WIDGET_MIN_WIDTH = 300;
const WIDGET_MAX_WIDTH = 620;
// Match the single-line quota footer; keep two complete account rows at minimum height.
const WIDGET_BASE_HEIGHT = 415;
const WIDGET_ACCOUNT_ROW_DELTA = 49;
const WIDGET_MIN_ACCOUNT_ROWS = 2;
const WIDGET_MIN_HEIGHT = WIDGET_BASE_HEIGHT + (WIDGET_MIN_ACCOUNT_ROWS - 1) * WIDGET_ACCOUNT_ROW_DELTA;
const VALID_RESIZE_EDGES = new Set(["n", "e", "s", "w", "ne", "se", "sw", "nw"]);
const WIDGET_DOCK_EDGE_THRESHOLD = 12;
const WIDGET_DOCK_VISIBLE_SIZE = 12;
const WIDGET_DOCK_SETTLE_MS = 180;
const WIDGET_DOCK_COLLAPSE_MS = 420;
const WIDGET_DOCK_SUPPRESS_MOVE_MS = 280;
const WIDGET_DOCK_POLL_MS = 90;
const WIDGET_DOCK_STRIP_GRACE = 4;
const WIDGET_DOCK_COLLAPSE_VERIFY_MS = 260;
const WIDGET_DOCK_COLLAPSE_RETRY_MS = 360;
const WIDGET_DOCK_COLLAPSE_RETRY_LIMIT = 8;
const ATOMIC_TEMP_MAX_AGE_MS = 60 * 60 * 1000;
const AUTH_BACKUP_RETENTION_COUNT = 60;
const localDataCache = createLocalDataCache();
const quotaDesktopBridge = createDesktopBridge();
const desktopQuotaReader = createDesktopQuotaReader({
getAnchor: () => isWindows ? readLocalThreadAnchor(codexDir()) : null,
readUsage: (anchor) => quotaDesktopBridge.readUsage(anchor),
getScope: dashboardScope,
onUpdate: async (scope, quota) => {
if (await saveAccountQuotaSnapshot(scope.accountId, quota, scope.since)) {
localDataCache.invalidate();
broadcastStateChanged({ scope: "quota" });
}
},
});
let mainWindow;
let widgetWindow;
let tray;
let isQuitting = false;
let widgetAlwaysOnTop = false;
let widgetManualSize = false;
let widgetAccountCount = WIDGET_MIN_ACCOUNT_ROWS;
let widgetResizeSession = null;
let widgetBoundsSaveTimer;
let runtimeSettings = null;
let widgetDockState = {
edge: null,
expandedBounds: null,
collapsed: false,
edgeHoverArmed: true,
hintEdge: null,
pointerInside: false,
settleTimer: null,
collapseTimer: null,
verifyTimer: null,
pollTimer: null,
collapseRetryCount: 0,
suppressMoveUntil: 0,
};
let authWatcher;
let authSyncTimer;
let authSyncInterval;
let localLogWatcher;
let localLogRefreshTimer;
let localLogRefreshInFlight = false;
let localLogRefreshPending = false;
let sessionsWatcher;
let sessionsPollingInterval;
let lastKnownLocalQuotaMtimeMs = 0;
let indexMutationQueue = Promise.resolve();
let accountOperationQueue = Promise.resolve();
let tokenLedgerQueue = Promise.resolve();
const sessionParseCache = new Map();
const quotaEventParseCache = new Map();
const sqliteResponseEventCache = new Map();
const reauthCheckTimers = new Map();
const hasSingleInstanceLock = app.requestSingleInstanceLock();
let startupReady = false;
let pendingWindow = null;
if (!hasSingleInstanceLock) {
app.quit();
} else {
app.on("second-instance", (_event, argv) => {
if (!startupReady) {
pendingWindow = hasStartupArg(argv) ? "widget" : "main";
return;
}
if (hasStartupArg(argv)) {
showWidgetWindow();
return;
}
showMainWindow();
});
}
function codexDir() {
return resolveCodexHome(process.env, os.homedir());
}
function authPath() {
return path.join(codexDir(), "auth.json");
}
function codexConfigPath() {
return path.join(codexDir(), "config.toml");
}
function sessionsDir() {
return path.join(codexDir(), "sessions");
}
function sessionIndexPath() {
return path.join(codexDir(), "session_index.jsonl");
}
function logsDbPath() {
if (selectedLogsDb && Date.now() - selectedLogsDbAt < 30000) return selectedLogsDb;
try {
const names = fsSync.readdirSync(codexDir()).filter((name) => /^logs_\d+\.sqlite$/.test(name));
names.sort((a,b) => Number(b.match(/\d+/)[0]) - Number(a.match(/\d+/)[0]));
selectedLogsDb = path.join(codexDir(), names[0] ?? "logs_2.sqlite");
} catch { selectedLogsDb = path.join(codexDir(), "logs_2.sqlite"); }
selectedLogsDbAt = Date.now();
return selectedLogsDb;
}
function logsDbWalPath() {
return `${logsDbPath()}-wal`;
}
function logsDbShmPath() {
return `${logsDbPath()}-shm`;
}
function storeRoot() {
return path.join(app.getPath("appData"), STORE_DIR_NAME);
}
function indexPath() {
return path.join(storeRoot(), "accounts.json");
}
function accountsDir() {
return path.join(storeRoot(), "accounts");
}
function accountBlobPath(id) {
return path.join(accountsDir(), `${id}.${credentialFileExtension()}`);
}
function backupsDir() {
return path.join(storeRoot(), "backups");
}
function tokenLedgerPath() {
return path.join(storeRoot(), "local-token-ledger.json");
}
function appIconPngPath() {
return path.join(__dirname, "ui", "assets", "codex-color.png");
}
function appIconIcoPath() {
return path.join(__dirname, "ui", "assets", "codex-color.ico");
}
function appIconPath() {
return isWindows ? appIconIcoPath() : appIconPngPath();
}
function trayIconIcoPath() {
return path.join(__dirname, "ui", "assets", "codex-color-tray.ico");
}
function widgetHeightForAccounts(accountCount) {
const numericCount = Number(accountCount);
const count = Number.isFinite(numericCount) ? Math.max(0, Math.floor(numericCount)) : 0;
const visibleRows = Math.max(WIDGET_MIN_ACCOUNT_ROWS, count);
return WIDGET_BASE_HEIGHT + (visibleRows - 1) * WIDGET_ACCOUNT_ROW_DELTA;
}
function widgetMaxHeightForBounds(bounds, accountCount = widgetAccountCount) {
const workArea = screen.getDisplayMatching(bounds).workArea;
const availableHeight = Math.max(WIDGET_MIN_HEIGHT, workArea.height - 16);
return Math.max(
WIDGET_MIN_HEIGHT,
Math.min(widgetHeightForAccounts(accountCount), availableHeight)
);
}
function normalizeWidgetBounds(bounds) {
if (!bounds || typeof bounds !== "object") return null;
const x = Math.round(Number(bounds.x));
const y = Math.round(Number(bounds.y));
const width = Math.round(Number(bounds.width));
const height = Math.round(Number(bounds.height));
if (![x, y, width, height].every(Number.isFinite)) return null;
return {
x,
y,
width: clamp(width, WIDGET_MIN_WIDTH, WIDGET_MAX_WIDTH),
height: Math.max(WIDGET_MIN_HEIGHT, height),
};
}
async function ensureStoreDirs() {
await fs.mkdir(accountsDir(), { recursive: true });
await fs.mkdir(backupsDir(), { recursive: true });
}
async function pruneAuthBackups() {
let entries;
try {
entries = await fs.readdir(backupsDir(), { withFileTypes: true });
} catch {
return { removedFiles: 0, removedBytes: 0 };
}
const backups = [];
for (const entry of entries) {
if (!entry.isFile() || !isEncryptedCredentialBackup(entry.name)) continue;
const filePath = path.join(backupsDir(), entry.name);
try {
const stat = await fs.stat(filePath);
backups.push({ filePath, size: stat.size, mtimeMs: stat.mtimeMs });
} catch {
// A concurrent cleanup may have already removed the file.
}
}
backups.sort((a, b) => b.mtimeMs - a.mtimeMs);
let removedFiles = 0;
let removedBytes = 0;
for (const backup of backups.slice(AUTH_BACKUP_RETENTION_COUNT)) {
try {
await fs.rm(backup.filePath, { force: true });
removedFiles += 1;
removedBytes += backup.size;
} catch {
// Retention cleanup is best-effort and must not block account switching.
}
}
return { removedFiles, removedBytes };
}
async function cleanupStoreArtifacts() {
const cutoffMs = Date.now() - ATOMIC_TEMP_MAX_AGE_MS;
let entries;
try {
entries = await fs.readdir(storeRoot(), { withFileTypes: true });
} catch {
entries = [];
}
let removedFiles = 0;
let removedBytes = 0;
for (const entry of entries) {
if (
!entry.isFile() ||
!/^(?:accounts\.json|local-token-ledger\.json)\.tmp-[0-9a-f-]+$/i.test(entry.name)
) {
continue;
}
const filePath = path.join(storeRoot(), entry.name);
try {
const stat = await fs.stat(filePath);
if (stat.mtimeMs > cutoffMs) continue;
await fs.rm(filePath, { force: true });
removedFiles += 1;
removedBytes += stat.size;
} catch {
// Stale temporary files are harmless if a cleanup race occurs.
}
}
const backupCleanup = await pruneAuthBackups();
return {
removedFiles: removedFiles + backupCleanup.removedFiles,
removedBytes: removedBytes + backupCleanup.removedBytes,
};
}
async function pathExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
async function readJson(filePath, fallback) {
try {
const raw = await fs.readFile(filePath, "utf8");
return JSON.parse(raw);
} catch (error) {
if (error.code === "ENOENT") {
return fallback;
}
throw error;
}
}
async function writeJsonAtomic(filePath, value, options = {}) {
await fs.mkdir(path.dirname(filePath), { recursive: true });
const temp = `${filePath}.tmp-${crypto.randomUUID()}`;
const content = `${options.pretty === false ? JSON.stringify(value) : JSON.stringify(value, null, 2)}\n`;
try {
await fs.writeFile(temp, content, { encoding: "utf8", mode: 0o600 });
await fs.rename(temp, filePath);
} finally {
await fs.rm(temp, { force: true }).catch(() => {});
}
}
async function writeTextAtomic(filePath, content) {
await fs.mkdir(path.dirname(filePath), { recursive: true });
const temp = `${filePath}.tmp-${crypto.randomUUID()}`;
try {
await fs.writeFile(temp, content, { encoding: "utf8", mode: 0o600 });
await fs.rename(temp, filePath);
} finally {
await fs.rm(temp, { force: true }).catch(() => {});
}
}
async function ensureCodexFileCredentialStore() {
const configFile = codexConfigPath();
let current = "";
let existed = true;
try {
current = await fs.readFile(configFile, "utf8");
} catch (error) {
if (error.code !== "ENOENT") throw error;
existed = false;
}
const next = fileCredentialStoreConfig(current);
if (!next.changed) return { changed: false, path: configFile };
await fs.mkdir(codexDir(), { recursive: true });
if (existed) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
await fs.copyFile(configFile, `${configFile}.codexauth-backup-${stamp}`);
}
await writeTextAtomic(configFile, next.content);
return { changed: true, path: configFile };
}
function defaultSettings() {
return {
language: "zh-CN",
quotaMode: QUOTA_MODE_LOCAL,
launchAtLogin: false,
restartAfterSwitch: true,
autoSwitchOnLimit: false,
autoResetOnWeeklyLimit: false,
autoSwitchEnabledAt: null,
widgetBounds: null,
recoveryCountdownPosition: null,
};
}
function normalizeSettings(settings) {
const normalized = {
...defaultSettings(),
...settings,
quotaMode: QUOTA_MODE_LOCAL,
};
return {
...normalized,
language: normalizeLanguage(normalized.language),
launchAtLogin: normalized.launchAtLogin === true,
restartAfterSwitch: normalized.restartAfterSwitch !== false,
autoSwitchOnLimit: normalized.autoSwitchOnLimit === true,
autoResetOnWeeklyLimit: normalized.autoResetOnWeeklyLimit === true,
autoSwitchEnabledAt: Number.isFinite(normalized.autoSwitchEnabledAt) ? normalized.autoSwitchEnabledAt : null,
widgetBounds: normalizeWidgetBounds(normalized.widgetBounds),
recoveryCountdownPosition: normalizeCountdownPosition(normalized.recoveryCountdownPosition),
};
}
function loginItemIdentityOptions() {
const args = app.isPackaged ? [STARTUP_ARG] : [app.getAppPath(), STARTUP_ARG];
const options = {
name: APP_NAME,
path: process.execPath,
args,
};
return options;
}
function applyLaunchAtLogin(enabled) {
const openAtLogin = enabled === true;
app.setLoginItemSettings({
...loginItemIdentityOptions(),
openAtLogin,
openAsHidden: true,
});
return openAtLogin;
}
function hasStartupArg(argv = process.argv) {
return Array.isArray(argv) && argv.includes(STARTUP_ARG);
}
function wasOpenedFromLoginItem() {
if (hasStartupArg()) return true;
try {
const loginSettings = app.getLoginItemSettings(loginItemIdentityOptions());
return loginSettings.wasOpenedAtLogin === true || loginSettings.wasOpenedAsHidden === true;
} catch {
return false;
}
}
function shouldStartWithWidgetOnly(settings) {
return settings?.launchAtLogin === true && wasOpenedFromLoginItem();
}
function normalizeSettingsForState(settings) {
return normalizeSettings(settings);
}
async function readIndex() {
const fallback = { version: STORE_VERSION, activeAccountId: null, accounts: [], deletedIdentityKeys: [], settings: defaultSettings() };
const data = await readJson(indexPath(), fallback);
return {
version: STORE_VERSION,
activeAccountId: data.activeAccountId ?? null,
accounts: Array.isArray(data.accounts) ? data.accounts : [],
deletedIdentityKeys: Array.isArray(data.deletedIdentityKeys) ? data.deletedIdentityKeys : [],
settings: normalizeSettings(data.settings),
recovery: data.recovery ?? null,
};
}
async function writeIndex(index) {
await writeJsonAtomic(indexPath(), {
version: STORE_VERSION,
activeAccountId: index.activeAccountId ?? null,
accounts: index.accounts,
deletedIdentityKeys: Array.isArray(index.deletedIdentityKeys) ? index.deletedIdentityKeys : [],
settings: normalizeSettings(index.settings),
recovery: index.recovery ?? null,
});
}
async function waitForIndexMutations() {
await indexMutationQueue.catch(() => {});
}
async function mutateIndex(mutator) {
const previous = indexMutationQueue;
let release;
indexMutationQueue = new Promise((resolve) => {
release = resolve;
});
await previous.catch(() => {});
try {
const index = await readIndex();
const result = (await mutator(index)) ?? {};
if (result.write !== false) {
await writeIndex(index);
}
return result.value;
} finally {
release();
}
}
async function runAccountOperation(task) {
const previous = accountOperationQueue;
let release;
accountOperationQueue = new Promise((resolve) => {
release = resolve;
});
await previous.catch(() => {});
try {
await onlineAccounts?.flushPending();
return await task();
} finally {
release();
}
}
async function runTokenLedgerOperation(task) {
const previous = tokenLedgerQueue;
let release;
tokenLedgerQueue = new Promise((resolve) => {
release = resolve;
});
await previous.catch(() => {});
try {
return await task();
} finally {
release();
}
}
function runProcess(command, args = [], stdinText = "") {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { windowsHide: true });
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => {
stdout += chunk;
});
child.stderr.on("data", (chunk) => {
stderr += chunk;
});
child.on("error", reject);
child.on("close", (code) => {
if (code === 0) {
resolve(stdout.trim());
return;
}
const error = new Error((stderr || stdout || `${command} exited with ${code}`).trim());
error.exitCode = code;
reject(error);
});
child.stdin.end(stdinText);
});
}
function runPowerShell(script, stdinText = "") {
return runProcess(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command",
"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false);\n" + script],
stdinText
);
}
async function protectText(plainText) {
if (isMac) {
if (!safeStorage.isEncryptionAvailable()) {
throw new Error("macOS Keychain encryption is unavailable for the current user.");
}
return safeStorage.encryptString(plainText).toString("base64");
}
if (!isWindows) {
throw new Error("Credential storage is supported on Windows and macOS only.");
}
const input = Buffer.from(plainText, "utf8").toString("base64");
const script = `
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Security
$inputText = [Console]::In.ReadToEnd()
$bytes = [Convert]::FromBase64String($inputText.Trim())
$protected = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
[Console]::Out.Write([Convert]::ToBase64String($protected))
`;
return runPowerShell(script, input);
}
async function unprotectText(cipherText) {
if (isMac) {
if (!safeStorage.isEncryptionAvailable()) {
throw new Error("macOS Keychain encryption is unavailable for the current user.");
}
return safeStorage.decryptString(Buffer.from(String(cipherText).trim(), "base64"));
}
if (!isWindows) {
throw new Error("Credential storage is supported on Windows and macOS only.");
}
const script = `
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Security
$inputText = [Console]::In.ReadToEnd()
$bytes = [Convert]::FromBase64String($inputText.Trim())
$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
[Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))
`;
return runPowerShell(script, cipherText);
}
function base64UrlDecode(input) {
const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), "=");
return Buffer.from(padded, "base64").toString("utf8");
}
function decodeJwtPayload(token) {
if (typeof token !== "string") return null;
const parts = token.split(".");
if (parts.length < 2) return null;
try {
return JSON.parse(base64UrlDecode(parts[1]));
} catch {
return null;
}
}
function nestedClaim(payload, key) {
const nested = payload?.["https://api.openai.com/auth"];
return typeof nested?.[key] === "string" ? nested[key] : null;
}
function extractIdentity(authJson) {
const tokens = authJson?.tokens ?? {};
const accessPayload = decodeJwtPayload(tokens.access_token);
const idPayload = decodeJwtPayload(tokens.id_token);
const email =
(typeof idPayload?.email === "string" && idPayload.email) ||
nestedClaim(idPayload, "email") ||
nestedClaim(accessPayload, "email") ||
null;
const userId =
(typeof accessPayload?.chatgpt_account_id === "string" && accessPayload.chatgpt_account_id) ||
nestedClaim(accessPayload, "chatgpt_account_id") ||
(typeof idPayload?.chatgpt_account_id === "string" && idPayload.chatgpt_account_id) ||
nestedClaim(idPayload, "chatgpt_account_id") ||
null;
const subject =
(typeof idPayload?.sub === "string" && idPayload.sub) ||
(typeof accessPayload?.sub === "string" && accessPayload.sub) ||
null;
const accountUserId =
nestedClaim(accessPayload, "chatgpt_account_user_id") ||
nestedClaim(idPayload, "chatgpt_account_user_id") ||
null;
const chatgptUserId =
nestedClaim(accessPayload, "chatgpt_user_id") ||
nestedClaim(idPayload, "chatgpt_user_id") ||
nestedClaim(accessPayload, "user_id") ||
nestedClaim(idPayload, "user_id") ||
null;
const planType =
nestedClaim(accessPayload, "chatgpt_plan_type") ||
nestedClaim(idPayload, "chatgpt_plan_type") ||
null;
const identity = { email, userId, subject, accountUserId, chatgptUserId, planType };
return { ...identity, subscription: subscriptionFromClaims([accessPayload, idPayload], identity) };
}
function tokenExpirySeconds(token) {
const payload = decodeJwtPayload(token);
return typeof payload?.exp === "number" ? payload.exp : null;
}
function authTokenStatus(parsed) {
const accessExp = tokenExpirySeconds(parsed?.tokens?.access_token);
const accessTokenExpiresAt = accessExp ? new Date(accessExp * 1000).toISOString() : null;
return {
accessTokenExpiresAt,
accessTokenExpired: accessExp ? accessExp * 1000 <= Date.now() : null,
};
}
function validateAuthJson(content) {
let parsed;
try {
parsed = JSON.parse(content);
} catch {
throw new Error("auth.json is not valid JSON.");
}
if (parsed.auth_mode !== "chatgpt") {
throw new Error("Only Codex App ChatGPT sign-in auth is supported in this app.");
}
const tokens = parsed.tokens ?? {};
if (!tokens.access_token || !tokens.refresh_token) {
throw new Error("auth.json is missing access_token or refresh_token.");
}
const identity = extractIdentity(parsed);
if (!identity.email && !identity.userId && !identity.subject) {
throw new Error("Cannot identify this Codex account from auth.json.");
}
return { parsed, identity };
}
function identityKey(identity) {
// Business/workspace ids and person ids are not unique enough by themselves:
// same Business workspace can have multiple people, and one person can belong to multiple workspaces.
const personKey = identity.subject || identity.email || null;
const workspaceKey = identity.userId || null;
if (personKey && workspaceKey) return `${personKey}::${workspaceKey}`;
return personKey || workspaceKey || null;
}
function safeAccountName(input, identity) {
const fallback = identity.email || identity.userId || identity.subject || "Codex Account";
const trimmed = typeof input === "string" ? input.trim() : "";
return trimmed || fallback;
}
function createAccountRecord(auth, displayName, now) {
const account = {
id: crypto.randomUUID(),
displayName,
identity: auth.identity,
createdAt: now,
updatedAt: now,
lastRefresh: authLastRefresh(auth.parsed),
authFingerprint: fingerprint(auth.content),
refreshTokenFingerprint: refreshTokenFingerprint(auth.parsed),
lastSwitchedAt: now,
};
Object.assign(account, authTokenStatus(auth.parsed));
return account;
}
function fingerprint(content) {
return crypto.createHash("sha256").update(content).digest("hex");
}
async function readCurrentAuth() {
const currentPath = authPath();
const content = await fs.readFile(currentPath, "utf8");
const validation = validateAuthJson(content);
return { path: currentPath, content, ...validation };
}
async function recoverStoreIfNeeded() {
return recoverAccountIndex({
indexPath:indexPath(), accountsDir:accountsDir(), extension:credentialFileExtension(),
decode:async (encrypted) => {
const content=await unprotectText(encrypted);
return {...validateAuthJson(content),content};
},
identify:identityKey,
makeRecord:(auth) => createAccountRecord(auth,safeAccountName("",auth.identity),new Date().toISOString()),
write:writeJsonAtomic,
});
}
async function readLocalRecords(files, since = null) {
const cutoff=since ? Date.parse(since) : null;
const records=[];
records.complete = true;
for(const file of files) {
if(Number.isFinite(cutoff) && file.mtimeMs < cutoff) continue;
try { records.push(await readRecordFile(file)); } catch { records.complete = false; /* surfaced as failedFiles in statistics */ }
}
return records;
}
async function localDiagnostics(index, current) {
if (!detectedCodexVersion) {
detectedCodexVersion = (async () => {
try {
if (isWindows) {
const output = await runPowerShell("$p = Get-AppxPackage -Name 'OpenAI.Codex' -ErrorAction SilentlyContinue | Sort-Object Version -Descending | Select-Object -First 1; if ($p) { $p.Version.ToString() }");
return String(output).trim().slice(0,80) || null;
}
} catch { /* version detection is optional */ }
return null;
})();
}
const config=await fs.readFile(codexConfigPath(),"utf8").catch(()=>"");
const files=await localDataCache.getSessionFiles(sessionsDir(),walkSessionFiles);
let dbReadable=false;
try {
const {DatabaseSync}=require("node:sqlite");const db=new DatabaseSync(logsDbPath(),{readOnly:true});
try { const columns=db.prepare("pragma table_info(logs)").all().map((c)=>c.name);dbReadable=columns.includes("ts")&&columns.includes("feedback_log_body"); } finally {db.close();}
} catch { /* sessions remain available without SQLite */ }
const matching=index.accounts.find((a)=>a.authFingerprint===current?.fingerprint);
return {version:app.getVersion(),codexVersion:await detectedCodexVersion,
fileCredentials:!fileCredentialStoreConfig(config).changed,
authRecognized:!!current?.exists&&!current?.error, authSynchronized:!!matching,
accountCount:index.accounts.length,logDatabase:path.basename(logsDbPath()),dbReadable,
sessionFiles:files.length,latestLogAt:files[0]?.mtimeMs?new Date(files[0].mtimeMs).toISOString():null,
recovery:index.recovery??null, mode:"local-usage-and-online-standby-quota"};
}
async function readLocalResetCredits(scope, records) {
const since=Date.parse(scope.since);
let latest=records.flatMap((r)=>r.resets).filter((r)=>Date.parse(r.checkedAt)>=since)
.sort((a,b)=>Date.parse(b.checkedAt)-Date.parse(a.checkedAt))[0]??null;
// Only structured Codex messages with matching account tags are accepted.
// Assistant/tool transcripts (including quota queries pasted in a chat) are
// intentionally not a data source for earned-reset balances.
const fromDb=Number.isFinite(since) ? await localDataCache.cached(`reset:${scope.accountId}:${scope.since}`,async()=>{
let db;
try {
const {DatabaseSync}=require("node:sqlite");db=new DatabaseSync(logsDbPath(),{readOnly:true});
const rows=db.prepare("select ts, feedback_log_body from logs where ts >= ? and (feedback_log_body like '%rateLimitResetCredits%' or feedback_log_body like '%rate_limit_reset_credits%') order by ts desc, id desc limit 100").all(Math.floor(since/1000));
const filter=normalizeAccountFilter(scope.account);
for(const row of rows){
const fields=parseLogKeyValues(row.feedback_log_body);
if(responseEventAccountMatch({accountId:fields["user.account_id"],email:fields["user.email"]},filter)!=="match" || !fields["user.account_id"])continue;
const message=extractCodexLogMessage(row.feedback_log_body);
if(!["codex.rate_limits","account/rateLimits/updated"].includes(message?.type??message?.method))continue;
const data=message.params??message;
const result=normalizeResetCredits(data.rateLimitResetCredits??data.rate_limit_reset_credits,new Date(row.ts*1000).toISOString());
if(result)return result;
}
}catch{/* an absent local reset record means unknown, never zero */}
finally{db?.close();}
return null;
}) : null;
if(fromDb&&(!latest||Date.parse(fromDb.checkedAt)>Date.parse(latest.checkedAt)))latest=fromDb;
const browser = scope.hasCurrentAuth ? await localDataCache.cached(`browser-reset:${scope.accountId}`, () =>
readBrowserResetCredits(app.getPath("appData"), scope.account)) : null;
if (browser && (!latest || Date.parse(browser.checkedAt) > Date.parse(latest.checkedAt))) latest = browser;
return latest;
}
async function loadAccountAuth(accountId) {
const encrypted = await fs.readFile(accountBlobPath(accountId), "utf8");
return unprotectText(encrypted);
}
async function saveAccountAuth(accountId, content) {
await ensureStoreDirs();
const encrypted = await protectText(content);
await writeTextAtomic(accountBlobPath(accountId), `${encrypted}\n`);
}
function authLastRefresh(parsed) {
return typeof parsed?.last_refresh === "string" ? parsed.last_refresh : null;
}
function refreshTokenFingerprint(parsed) {
const refreshToken = parsed?.tokens?.refresh_token;
return typeof refreshToken === "string" && refreshToken ? fingerprint(refreshToken) : null;
}
function markAccountAuthSnapshot(account, auth, content, now, { trustedLogin = false } = {}) {
const nextRefreshTokenFingerprint = refreshTokenFingerprint(auth.parsed);
if (
account.refreshTokenFingerprint &&
nextRefreshTokenFingerprint &&
account.refreshTokenFingerprint !== nextRefreshTokenFingerprint
) {
account.refreshTokenRotatedAt = now;
}
account.identity = auth.identity;
account.updatedAt = now;
account.lastRefresh = authLastRefresh(auth.parsed);
account.authFingerprint = fingerprint(content);
account.refreshTokenFingerprint = nextRefreshTokenFingerprint;
Object.assign(account, authTokenStatus(auth.parsed));
// Reading/importing a structurally valid file does not prove a live login.
if (trustedLogin) {
delete account.needsReauth;
delete account.reauthReason;
delete account.reauthMarkedAt;
}
}
function getOnlineAccounts() {
if (onlineAccounts) return onlineAccounts;
onlineAccounts = createOnlineAccounts({
runExclusive: runAccountOperation,
resetEnabled: () => runtimeSettings?.autoSwitchOnLimit === true && runtimeSettings?.autoResetOnWeeklyLimit === true,
readAccount: async (id) => {
const index = await readIndex();
const account = index.accounts.find((item) => item.id === id);
if (!account) return null;
let current = null;
try { current = await readCurrentAuth(); } catch (error) { if (error.code !== "ENOENT") throw error; }
const active = index.activeAccountId === id || (current && identityKey(current.identity) === identityKey(account.identity));
if (active) return { account, active: true };
const content = await loadAccountAuth(id);
const auth = validateAuthJson(content);
if (!account.identity?.userId || identityKey(auth.identity) !== identityKey(account.identity)) throw new Error("账号身份不匹配。");
return { account, content, active: false };
},
validateRenewal: (before, after) => {
const original = validateAuthJson(before), updated = validateAuthJson(after);
if (identityKey(original.identity) !== identityKey(updated.identity)) throw new Error("续期返回的账号身份不匹配。");
},
saveAuth: (id, previous, next) => mutateIndex(async (index) => {
const account = index.accounts.find((item) => item.id === id);
if (!account) throw new Error("账号已删除。");
const stored = await loadAccountAuth(id);
if (stored !== previous && stored !== next) throw new Error("账号凭据已改变。");
const auth = validateAuthJson(next);
if (identityKey(account.identity) !== identityKey(auth.identity)) throw new Error("续期身份不匹配。");
// Persist the rotated refresh token first. Retrying an index write must
// never send the old refresh token again or overwrite the live auth file.
if (stored !== next) await saveAccountAuth(id, next);
markAccountAuthSnapshot(account, auth, next, new Date().toISOString(), { trustedLogin: true });
}),
saveQuota: (id, content, quota) => mutateIndex(async (index) => {
const account = index.accounts.find((item) => item.id === id);
if (!account || await loadAccountAuth(id) !== content || account.identity?.userId !== quota.accountId) throw new Error("账号状态已改变。");
if (Date.parse(account.quotaSnapshot?.checkedAt) > Date.parse(quota.checkedAt)) return { write: false };
account.quotaSnapshot = { ...quota, identityKey: identityKey(account.identity) };
account.quotaSnapshotUpdatedAt = quota.checkedAt;
account.onlineQuotaStatus = { checkedAt: quota.checkedAt, error: null };
delete account.needsReauth;
delete account.reauthReason;
delete account.reauthMarkedAt;
localDataCache.invalidate();
broadcastStateChanged({ scope: "accounts" });
}),
saveResetAttempt: (id, content, attempt) => mutateIndex(async (index) => {
const account = index.accounts.find((item) => item.id === id);
if (!account || await loadAccountAuth(id) !== content || account.identity?.userId !== attempt.accountId) throw new Error("账号状态已改变。");
account.autoResetAttempt = attempt;
}),
saveStatus: (id, content, status) => mutateIndex(async (index) => {