claude-codex-proxy 1.0.1 → 1.0.3

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 CHANGED
@@ -4,12 +4,12 @@
4
4
 
5
5
  [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/)
6
6
  [![Node.js Version](https://img.shields.io/badge/Node.js-18%2B-blue.svg)](https://nodejs.org/)
7
- [![GitHub stars](https://img.shields.io/github/stars/zzy-life/codex-claude-proxy?style=social)](https://github.com/zzy-life/codex-claude-proxy)
7
+ [![GitHub stars](https://img.shields.io/github/stars/zzy-life/claude-codex-proxy?style=social)](https://github.com/zzy-life/claude-codex-proxy)
8
8
 
9
9
  > **Use Claude Code CLI with the power of ChatGPT Codex models.**
10
10
  > A local proxy that translates Anthropic API requests into ChatGPT Codex calls, enabling you to use the `claude` CLI tool with your ChatGPT Free/Plus/Pro subscription.
11
11
 
12
- > This project is forked from the original `codex-claude-proxy` project and maintained with additional changes for this distribution.
12
+ > This project is forked from the original Claude/Codex proxy project and maintained with additional changes for this distribution.
13
13
 
14
14
  ---
15
15
 
@@ -234,7 +234,7 @@ This project is an independent open-source tool and is not affiliated with, endo
234
234
 
235
235
  <div align="center">
236
236
  <p>If you find this project useful, please give it a star! ⭐️</p>
237
- <a href="https://github.com/zzy-life/codex-claude-proxy">
238
- <img src="https://img.shields.io/github/stars/zzy-life/codex-claude-proxy?style=social" alt="Star on GitHub">
237
+ <a href="https://github.com/zzy-life/claude-codex-proxy">
238
+ <img src="https://img.shields.io/github/stars/zzy-life/claude-codex-proxy?style=social" alt="Star on GitHub">
239
239
  </a>
240
- </div>
240
+ </div>
package/docs/ACCOUNTS.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  ### Main Registry
6
6
 
7
- **Location:** `~/.codex-claude-proxy/accounts.json`
7
+ **Location:** `~/.claude-codex-proxy/accounts.json`
8
8
 
9
9
  ```json
10
10
  {
@@ -33,7 +33,7 @@
33
33
 
34
34
  ### Per-Account Tokens
35
35
 
36
- **Location:** `~/.codex-claude-proxy/accounts/<email>/auth.json`
36
+ **Location:** `~/.claude-codex-proxy/accounts/<email>/auth.json`
37
37
 
38
38
  ```json
39
39
  {
@@ -136,7 +136,7 @@ curl -X POST http://localhost:8081/accounts/refresh/all
136
136
 
137
137
  ### Auto-Refresh
138
138
 
139
- - Background refresh every **55 minutes**
139
+ - Background refresh every **5 hours**
140
140
  - Startup refresh 2 seconds after server start
141
141
  - Proactive refresh 5 minutes before expiry
142
142
 
@@ -196,7 +196,7 @@ On server startup:
196
196
 
197
197
  ## Security
198
198
 
199
- - Tokens stored locally in `~/.codex-claude-proxy/`
199
+ - Tokens stored locally in `~/.claude-codex-proxy/`
200
200
  - Directory permissions: user read/write only
201
201
  - Never logged or exposed in API responses
202
202
  - Per-account isolation via separate directories
@@ -24,7 +24,7 @@ This proxy forwards requests from Anthropic-compatible clients (like Claude Code
24
24
  ## Project Structure
25
25
 
26
26
  ```
27
- codex-claude-proxy/
27
+ claude-codex-proxy/
28
28
  ├── package.json
29
29
  ├── README.md
30
30
  ├── docs/
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -22,12 +22,12 @@
22
22
  },
23
23
  "repository": {
24
24
  "type": "git",
25
- "url": "git+https://github.com/zzy-life/codex-claude-proxy.git"
25
+ "url": "git+https://github.com/zzy-life/claude-codex-proxy.git"
26
26
  },
27
27
  "bugs": {
28
- "url": "https://github.com/zzy-life/codex-claude-proxy/issues"
28
+ "url": "https://github.com/zzy-life/claude-codex-proxy/issues"
29
29
  },
30
- "homepage": "https://github.com/zzy-life/codex-claude-proxy#readme",
30
+ "homepage": "https://github.com/zzy-life/claude-codex-proxy#readme",
31
31
  "scripts": {
32
32
  "start": "node src/index.js",
33
33
  "portfolio:dev": "npm --prefix apps/portfolio run dev",
@@ -57,6 +57,9 @@ body::before {
57
57
  .bg-neon-purple { background-color: var(--color-neon-purple); }
58
58
  .bg-neon-cyan { background-color: var(--color-neon-cyan); }
59
59
  .bg-neon-green { background-color: var(--color-neon-green); }
60
+ .bg-yellow-500 { background-color: #eab308; }
61
+ .bg-red-500 { background-color: #ef4444; }
62
+ .bg-gray-500 { background-color: #6b7280; }
60
63
 
61
64
  .border-neon-purple { border-color: var(--color-neon-purple); }
62
65
  .border-neon-cyan { border-color: var(--color-neon-cyan); }
package/public/index.html CHANGED
@@ -71,9 +71,9 @@
71
71
  <div class="flex flex-col gap-0.5">
72
72
  <div class="flex items-center gap-1.5">
73
73
  <span class="text-[10px] text-gray-500 font-mono tracking-wider">CLAUDE PROXY SYSTEM</span>
74
- <span class="text-[10px] text-gray-500 font-mono tracking-wider" x-text="'v' + version"></span>
74
+ <span class="text-[10px] text-gray-500 font-mono tracking-wider" x-text="version ? 'v' + version : ''"></span>
75
75
  </div>
76
- <a href="https://github.com/zzy-life/codex-claude-proxy" target="_blank" class="text-[10px] text-neon-purple hover:text-purple-400 hover:underline transition-colors flex items-center gap-1">
76
+ <a href="https://github.com/zzy-life/claude-codex-proxy" target="_blank" class="text-[10px] text-neon-purple hover:text-purple-400 hover:underline transition-colors flex items-center gap-1">
77
77
  <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>
78
78
  <span>Star on GitHub</span>
79
79
  </a>
@@ -316,7 +316,7 @@
316
316
  <thead x-show="filteredAccounts.length > 0">
317
317
  <tr class="bg-space-900/50 border-b border-space-border/50">
318
318
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-20">Status</th>
319
- <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider flex-1 min-w-[200px]">Account (Email)</th>
319
+ <th class="py-3 text-center text-[10px] font-bold text-gray-500 uppercase tracking-wider flex-1 min-w-[200px]">Account (Email)</th>
320
320
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-20">Plan</th>
321
321
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-32">Token</th>
322
322
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-24">Quota</th>
@@ -364,7 +364,7 @@
364
364
  </span>
365
365
  </div>
366
366
  </td>
367
- <td class="py-4">
367
+ <td class="py-4 text-center">
368
368
  <span class="font-mono text-sm text-gray-300 truncate max-w-[320px] inline-block group-hover:text-white transition-colors"
369
369
  x-text="acc.email"></span>
370
370
  </td>
@@ -382,6 +382,12 @@
382
382
  <span class="text-xs font-mono"
383
383
  :class="acc.tokenExpired ? 'text-red-400' : 'text-neon-green'"
384
384
  x-text="acc.tokenExpired ? 'Expired' : 'Valid'"></span>
385
+ <button class="btn btn-xs btn-ghost p-2 rounded hover:bg-white/10 text-gray-500 hover:text-white transition-colors"
386
+ @click="refreshToken(acc.email)" title="Refresh token">
387
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
388
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
389
+ </svg>
390
+ </button>
385
391
  </div>
386
392
  </td>
387
393
  <td class="py-4 cursor-pointer" @click="showQuotaModal(acc)">
@@ -415,16 +421,10 @@
415
421
  <td class="py-4 pr-6">
416
422
  <div class="flex justify-end gap-2">
417
423
  <button x-show="!acc.isActive"
418
- class="px-3 py-1 text-[10px] font-bold font-mono uppercase tracking-wider rounded bg-neon-purple/10 text-neon-purple hover:bg-neon-purple/20 border border-neon-purple/30 hover:border-neon-purple/50 transition-all"
424
+ class="cursor-pointer px-3 py-1 text-[10px] font-bold font-mono uppercase tracking-wider rounded bg-neon-purple/10 text-neon-purple hover:bg-neon-purple/20 border border-neon-purple/30 hover:border-neon-purple/50 transition-all"
419
425
  @click="switchAccount(acc.email)">
420
426
  SWITCH
421
427
  </button>
422
- <button class="btn btn-xs btn-ghost p-2 rounded hover:bg-white/10 text-gray-500 hover:text-white transition-colors"
423
- @click="refreshToken(acc.email)" title="Refresh token">
424
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
425
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
426
- </svg>
427
- </button>
428
428
  <button class="btn btn-xs btn-ghost p-2 rounded hover:bg-red-500/10 text-gray-500 hover:text-red-400 transition-colors"
429
429
  @click="confirmDelete(acc.email)" title="Delete account">
430
430
  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
package/public/js/app.js CHANGED
@@ -1,6 +1,6 @@
1
1
  document.addEventListener('alpine:init', () => {
2
2
  Alpine.data('app', () => ({
3
- version: '1.0.5',
3
+ version: '',
4
4
  connectionStatus: 'connecting',
5
5
  activeTab: 'dashboard',
6
6
  sidebarOpen: window.innerWidth >= 1024,
@@ -39,7 +39,7 @@ document.addEventListener('alpine:init', () => {
39
39
  testResponse: '',
40
40
  testing: false,
41
41
 
42
- configPath: '~/.codex-claude-proxy/accounts.json',
42
+ configPath: '~/.claude-codex-proxy/accounts.json',
43
43
 
44
44
  logs: [],
45
45
  logSearchQuery: '',
@@ -110,8 +110,9 @@ document.addEventListener('alpine:init', () => {
110
110
  },
111
111
 
112
112
  async checkHealth() {
113
- const { ok } = await this.api('/health');
113
+ const { ok, data } = await this.api('/health');
114
114
  this.connectionStatus = ok ? 'connected' : 'disconnected';
115
+ if (ok && data?.version) this.version = data.version;
115
116
  },
116
117
 
117
118
  async refreshAccounts() {
@@ -9,11 +9,12 @@ import { homedir } from 'os';
9
9
  import { refreshAccessToken, extractAccountInfo } from './oauth.js';
10
10
  import { getAccountQuota as fetchQuota } from './model-api.js';
11
11
 
12
- const CONFIG_DIR = join(homedir(), '.codex-claude-proxy');
12
+ const CONFIG_DIR = join(homedir(), '.claude-codex-proxy');
13
13
  const ACCOUNTS_FILE = join(CONFIG_DIR, 'accounts.json');
14
14
  const ACCOUNTS_DIR = join(CONFIG_DIR, 'accounts');
15
15
 
16
- const TOKEN_REFRESH_INTERVAL_MS = 55 * 60 * 1000;
16
+ const TOKEN_REFRESH_INTERVAL_MS = 5 * 60 * 60 * 1000;
17
+ const TOKEN_CACHE_TTL_MS = 55 * 60 * 1000;
17
18
  const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
18
19
 
19
20
  const DEFAULT_ACCOUNTS = {
@@ -228,8 +229,10 @@ function getAccountQuota(email) {
228
229
  }
229
230
 
230
231
  function isTokenExpiredOrExpiringSoon(account) {
231
- if (!account.expiresAt) return true;
232
- return Date.now() >= (account.expiresAt - TOKEN_EXPIRY_BUFFER_MS);
232
+ const info = account?.accessToken ? extractAccountInfo(account.accessToken) : null;
233
+ const expiresAt = info?.expiresAt || account?.expiresAt;
234
+ if (!expiresAt) return true;
235
+ return Date.now() >= (expiresAt - TOKEN_EXPIRY_BUFFER_MS);
233
236
  }
234
237
 
235
238
  async function refreshAccountToken(email) {
@@ -328,7 +331,7 @@ function startAutoRefresh() {
328
331
  }
329
332
  }, TOKEN_REFRESH_INTERVAL_MS);
330
333
 
331
- console.log('[AccountManager] Auto-refresh started (every 55 minutes)');
334
+ console.log('[AccountManager] Auto-refresh started (every 5 hours)');
332
335
  }
333
336
 
334
337
  function stopAutoRefresh() {
@@ -341,7 +344,7 @@ function stopAutoRefresh() {
341
344
 
342
345
  function getCachedToken(email) {
343
346
  const cached = tokenCache.get(email);
344
- if (cached && (Date.now() - cached.extractedAt) < TOKEN_REFRESH_INTERVAL_MS) {
347
+ if (cached && (Date.now() - cached.extractedAt) < TOKEN_CACHE_TTL_MS) {
345
348
  return cached.token;
346
349
  }
347
350
  return null;
@@ -499,6 +502,7 @@ export {
499
502
  getCachedToken,
500
503
  setCachedToken,
501
504
  TOKEN_REFRESH_INTERVAL_MS,
505
+ TOKEN_CACHE_TTL_MS,
502
506
  ACCOUNTS_FILE,
503
507
  CONFIG_DIR
504
508
  };
@@ -4,7 +4,8 @@ import {
4
4
  clearInvalid,
5
5
  isAllRateLimited,
6
6
  getMinWaitTimeMs,
7
- clearExpiredLimits
7
+ clearExpiredLimits,
8
+ isQuotaLimitReached
8
9
  } from './rate-limits.js';
9
10
 
10
11
  import { createStrategy, STRATEGIES } from './strategies/index.js';
@@ -13,11 +14,37 @@ export class AccountRotator {
13
14
  constructor(accountManager, strategyName = 'sticky') {
14
15
  this.accountManager = accountManager;
15
16
  this.strategy = createStrategy(strategyName);
17
+ this.currentIndex = null;
18
+ this.lastActiveEmail = null;
16
19
  }
17
20
 
18
21
  selectAccount(modelId, options = {}) {
19
22
  const { accounts } = this.accountManager.listAccounts();
20
- return this.strategy.selectAccount(accounts, modelId, options);
23
+ const strategyOptions = { ...options };
24
+
25
+ if (this.strategy.name === STRATEGIES.STICKY) {
26
+ const activeAccount = this.accountManager.getActiveAccount?.();
27
+ const activeEmail = activeAccount?.email || null;
28
+ const activeIndex = activeEmail
29
+ ? accounts.findIndex(account => account.email === activeEmail)
30
+ : -1;
31
+
32
+ if (this.currentIndex === null || activeEmail !== this.lastActiveEmail) {
33
+ this.currentIndex = activeIndex >= 0 ? activeIndex : 0;
34
+ this.lastActiveEmail = activeEmail;
35
+ }
36
+
37
+ strategyOptions.currentIndex = this.currentIndex;
38
+ strategyOptions.onSave = this.accountManager.save;
39
+ }
40
+
41
+ const result = this.strategy.selectAccount(accounts, modelId, strategyOptions);
42
+
43
+ if (this.strategy.name === STRATEGIES.STICKY && Number.isInteger(result.index)) {
44
+ this.currentIndex = result.index;
45
+ }
46
+
47
+ return result;
21
48
  }
22
49
 
23
50
  markRateLimited(email, resetMs, modelId) {
@@ -89,5 +116,6 @@ export {
89
116
  clearInvalid,
90
117
  isAllRateLimited,
91
118
  getMinWaitTimeMs,
92
- clearExpiredLimits
119
+ clearExpiredLimits,
120
+ isQuotaLimitReached
93
121
  };
@@ -17,10 +17,7 @@ const DEFAULT_COOLDOWN_MS = 60000;
17
17
  */
18
18
  export function isAllRateLimited(accounts, modelId) {
19
19
  if (!accounts || accounts.length === 0) return true;
20
- return accounts.every(account => {
21
- const rateLimit = account.modelRateLimits?.[modelId];
22
- return rateLimit?.isRateLimited && rateLimit.resetTime > Date.now();
23
- });
20
+ return getAvailableAccounts(accounts, modelId).length === 0;
24
21
  }
25
22
 
26
23
  /**
@@ -34,12 +31,19 @@ export function getAvailableAccounts(accounts, modelId) {
34
31
  const now = Date.now();
35
32
  return accounts.filter(account => {
36
33
  if (account.isInvalid) return false;
34
+ if (account.enabled === false) return false;
37
35
  if (isAccountCoolingDown(account)) return false;
36
+ if (isQuotaLimitReached(account)) return false;
38
37
  const rateLimit = account.modelRateLimits?.[modelId];
39
38
  return !rateLimit?.isRateLimited || rateLimit.resetTime <= now;
40
39
  });
41
40
  }
42
41
 
42
+ export function isQuotaLimitReached(account) {
43
+ const usage = account?.quota?.usage;
44
+ return usage?.allowed === false || usage?.limitReached === true;
45
+ }
46
+
43
47
  /**
44
48
  * Clear all expired rate limits across all accounts
45
49
  * @param {Array} accounts - Array of account objects
@@ -1,4 +1,4 @@
1
- import { isAccountCoolingDown } from '../rate-limits.js';
1
+ import { isAccountCoolingDown, isQuotaLimitReached } from '../rate-limits.js';
2
2
 
3
3
  export class BaseStrategy {
4
4
  constructor(config, name = 'base') {
@@ -24,7 +24,8 @@ export class BaseStrategy {
24
24
  if (account.isInvalid) return false;
25
25
  if (account.enabled === false) return false;
26
26
  if (isAccountCoolingDown(account)) return false;
27
-
27
+ if (isQuotaLimitReached(account)) return false;
28
+
28
29
  // Check model-specific rate limit
29
30
  if (modelId && account.modelRateLimits && account.modelRateLimits[modelId]) {
30
31
  const limit = account.modelRateLimits[modelId];
@@ -6,7 +6,6 @@ const MAX_WAIT_BEFORE_ERROR_MS = 120000;
6
6
  export class StickyStrategy extends BaseStrategy {
7
7
  constructor(config) {
8
8
  super(config, 'sticky');
9
- this.currentIndex = 0;
10
9
  }
11
10
 
12
11
  selectAccount(accounts, modelId, options = {}) {
@@ -32,7 +31,6 @@ export class StickyStrategy extends BaseStrategy {
32
31
  if (usableAccounts.length > 0) {
33
32
  const nextResult = this.#pickNext(accounts, clampedIndex, modelId, onSave);
34
33
  if (nextResult) {
35
- this.currentIndex = nextResult.index;
36
34
  return nextResult;
37
35
  }
38
36
  }
@@ -10,7 +10,7 @@ import { homedir } from 'os';
10
10
  import { join } from 'path';
11
11
  import crypto from 'crypto';
12
12
 
13
- const CONFIG_DIR = join(homedir(), '.codex-claude-proxy');
13
+ const CONFIG_DIR = join(homedir(), '.claude-codex-proxy');
14
14
  const ACCOUNTS_FILE = join(CONFIG_DIR, 'accounts.json');
15
15
  const DEFAULT_PORT = 8081;
16
16
 
package/src/direct-api.js CHANGED
@@ -39,27 +39,44 @@ function parseResetTime(response, errorText) {
39
39
  const seconds = parseInt(retryAfter, 10);
40
40
  if (!isNaN(seconds)) return seconds * 1000;
41
41
  }
42
-
42
+
43
43
  const ratelimitReset = response.headers?.get?.('x-ratelimit-reset');
44
44
  if (ratelimitReset) {
45
45
  const timestamp = parseInt(ratelimitReset, 10) * 1000;
46
46
  const wait = timestamp - Date.now();
47
47
  if (wait > 0) return wait;
48
48
  }
49
-
49
+
50
50
  if (errorText) {
51
+ try {
52
+ const errorData = JSON.parse(errorText);
53
+ const primaryWindow = errorData?.rate_limit?.primary_window || errorData?.error?.rate_limit?.primary_window;
54
+ const resetAfterSeconds = Number(primaryWindow?.reset_after_seconds);
55
+ if (Number.isFinite(resetAfterSeconds) && resetAfterSeconds > 0) {
56
+ return resetAfterSeconds * 1000;
57
+ }
58
+
59
+ const resetAt = Number(primaryWindow?.reset_at);
60
+ if (Number.isFinite(resetAt) && resetAt > 0) {
61
+ const wait = resetAt * 1000 - Date.now();
62
+ if (wait > 0) return wait;
63
+ }
64
+ } catch {
65
+ // Fall back to regex parsing for plain-text upstream errors.
66
+ }
67
+
51
68
  const delayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
52
69
  if (delayMatch) {
53
70
  const value = parseFloat(delayMatch[1]);
54
71
  return delayMatch[2] === 's' ? value * 1000 : value;
55
72
  }
56
-
73
+
57
74
  const secMatch = errorText.match(/retry\s+(?:after\s+)?(\d+)\s*(?:sec|s\b)/i);
58
75
  if (secMatch) {
59
76
  return parseInt(secMatch[1], 10) * 1000;
60
77
  }
61
78
  }
62
-
79
+
63
80
  return 60000;
64
81
  }
65
82
 
package/src/index.js CHANGED
@@ -40,7 +40,7 @@ console.log(`
40
40
  ╠══════════════════════════════════════════════════════════════╣
41
41
  ║ Support: ║
42
42
  ║ ★ Give it a star on GitHub! ║
43
- ║ https://github.com/zzy-life/codex-claude-proxy ║
43
+ ║ https://github.com/zzy-life/claude-codex-proxy ║
44
44
  ╚══════════════════════════════════════════════════════════════╝
45
45
  `);
46
46
 
package/src/oauth.js CHANGED
@@ -287,10 +287,19 @@ function startCallbackServer(expectedState, timeoutMs = 120000) {
287
287
  }
288
288
 
289
289
  if (code) {
290
+ if (state !== expectedState) {
291
+ console.error('[OAuth] State mismatch in callback');
292
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
293
+ res.end(getErrorHtml('Invalid OAuth state'));
294
+ server.close();
295
+ reject(new Error('Invalid OAuth state'));
296
+ return;
297
+ }
298
+
290
299
  console.log('[OAuth] Got authorization code');
291
300
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
292
301
  res.end(getSuccessHtml('Authentication Successful! You can close this window.'));
293
-
302
+
294
303
  setTimeout(() => {
295
304
  server.close();
296
305
  clearTimeout(timeoutId);
@@ -496,7 +505,7 @@ async function performOAuthFlow(customPort) {
496
505
  const authUrl = getAuthorizationUrl(verifier, state, port);
497
506
 
498
507
  // Start callback server
499
- const { promise: callbackPromise, server } = startCallbackServer(port, state);
508
+ const { promise: callbackPromise } = startCallbackServer(state);
500
509
 
501
510
  console.log(`\n[OAuth] Starting authentication flow...`);
502
511
  console.log(`[OAuth] Callback URL: http://localhost:${port}${OAUTH_CONFIG.callbackPath}`);
@@ -100,16 +100,16 @@ export async function handleAddAccount(req, res) {
100
100
  activeCallbackServers.set(callbackPort, serverResult);
101
101
 
102
102
  serverResult.promise
103
- .then(result => {
103
+ .then(code => {
104
104
  activeCallbackServers.delete(callbackPort);
105
- if (result?.code) {
106
- return exchangeCodeForTokens(result.code, verifier, callbackPort)
107
- .then(async tokens => {
108
- const accountInfo = extractAccountInfo(tokens);
109
- await _upsertAccount(accountInfo);
110
- logger.info(`Added account: ${accountInfo.email}`);
111
- });
112
- }
105
+ if (!code) return null;
106
+
107
+ return exchangeCodeForTokens(code, verifier, callbackPort)
108
+ .then(async tokens => {
109
+ const accountInfo = createAccountInfoFromTokens(tokens);
110
+ await _upsertAccount(accountInfo);
111
+ logger.info(`Added account: ${accountInfo.email}`);
112
+ });
113
113
  })
114
114
  .catch(err => {
115
115
  activeCallbackServers.delete(callbackPort);
@@ -135,7 +135,7 @@ export async function handleAddAccountManual(req, res) {
135
135
  try {
136
136
  const { code: extractedCode } = extractCodeFromInput(code);
137
137
  const tokens = await exchangeCodeForTokens(extractedCode, verifier);
138
- const accountInfo = extractAccountInfo(tokens);
138
+ const accountInfo = createAccountInfoFromTokens(tokens);
139
139
 
140
140
  await _upsertAccount(accountInfo);
141
141
  logger.info(`Added account via manual OAuth: ${accountInfo.email}`);
@@ -250,6 +250,22 @@ export async function handleGetAllQuotas(req, res) {
250
250
 
251
251
  // ─── Helpers ─────────────────────────────────────────────────────────────────
252
252
 
253
+ export function createAccountInfoFromTokens(tokens) {
254
+ const tokenInfo = extractAccountInfo(tokens.accessToken) || {};
255
+
256
+ return {
257
+ email: tokenInfo.email || 'unknown',
258
+ accountId: tokenInfo.accountId,
259
+ planType: tokenInfo.planType || 'free',
260
+ accessToken: tokens.accessToken,
261
+ refreshToken: tokens.refreshToken,
262
+ idToken: tokens.idToken,
263
+ expiresAt: tokenInfo.expiresAt || (Date.now() + tokens.expiresIn * 1000),
264
+ addedAt: new Date().toISOString(),
265
+ lastUsed: new Date().toISOString()
266
+ };
267
+ }
268
+
253
269
  /**
254
270
  * Inserts or updates an account in the persisted accounts store,
255
271
  * and sets it as the active account.
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import express from 'express';
8
+ import { createRequire } from 'module';
8
9
  import { join, dirname } from 'path';
9
10
  import { fileURLToPath } from 'url';
10
11
 
@@ -41,6 +42,8 @@ import {
41
42
  } from './accounts-route.js';
42
43
 
43
44
  const __dirname = dirname(fileURLToPath(import.meta.url));
45
+ const require = createRequire(import.meta.url);
46
+ const packageJson = require('../../package.json');
44
47
 
45
48
  export function registerApiRoutes(app, { port }) {
46
49
  // ─── Static Web UI ─────────────────────────────────────────────────────────
@@ -48,7 +51,7 @@ export function registerApiRoutes(app, { port }) {
48
51
 
49
52
  // ─── Health ────────────────────────────────────────────────────────────────
50
53
  app.get('/health', (req, res) => {
51
- res.json({ status: 'ok', ...getStatus(), configPath: ACCOUNTS_FILE });
54
+ res.json({ status: 'ok', version: packageJson.version, ...getStatus(), configPath: ACCOUNTS_FILE });
52
55
  });
53
56
 
54
57
  // ─── Anthropic Messages API ────────────────────────────────────────────────
@@ -4,7 +4,7 @@ import { sendAuthError, getCredentialsForAccount } from '../middleware/credentia
4
4
  import { initSSEResponse, pipeSSEStream, handleStreamError } from '../middleware/sse.js';
5
5
  import { logger } from '../utils/logger.js';
6
6
  import { AccountRotator } from '../account-rotation/index.js';
7
- import { listAccounts, getActiveAccount, save } from '../account-manager.js';
7
+ import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
8
8
  import { getServerSettings } from '../server-settings.js';
9
9
 
10
10
  const MAX_RETRIES = 5;
@@ -29,7 +29,14 @@ function getAccountRotator() {
29
29
 
30
30
  if (!accountRotator || currentStrategy !== strategy) {
31
31
  accountRotator = new AccountRotator({
32
- listAccounts,
32
+ listAccounts: () => {
33
+ const data = loadAccounts();
34
+ return {
35
+ accounts: data.accounts,
36
+ activeAccount: data.activeAccount,
37
+ total: data.accounts.length
38
+ };
39
+ },
33
40
  save,
34
41
  getActiveAccount
35
42
  }, strategy);
@@ -83,6 +90,9 @@ export async function handleMessages(req, res) {
83
90
  return sendAuthError(res, 'No available accounts');
84
91
  }
85
92
 
93
+ syncActiveAccount(account.email);
94
+ logger.info(`[Messages] Using account ${account.email} for model ${upstreamModel}`);
95
+
86
96
  const creds = await getCredentialsForAccount(account.email);
87
97
  if (!creds) {
88
98
  rotator.markInvalid(account.email, 'Failed to get credentials');
@@ -145,6 +155,16 @@ async function _sendDirectWithRotation(res, anthropicRequest, creds, responseMod
145
155
  res.json({ ...response, model: responseModel });
146
156
  }
147
157
 
158
+ function syncActiveAccount(email) {
159
+ const active = getActiveAccount();
160
+ if (active?.email === email) return;
161
+
162
+ const result = setActiveAccount(email);
163
+ if (result.success) {
164
+ logger.info(`[Messages] Synced active account to actual account: ${email}`);
165
+ }
166
+ }
167
+
148
168
  function getTokenDetails(usage = {}) {
149
169
  const inputTokens = usage?.input_tokens || 0;
150
170
  const outputTokens = usage?.output_tokens || 0;