claude-codex-proxy 1.0.4 → 1.0.5-beta.1

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
@@ -90,7 +90,22 @@ Other versions may work, but these versions are recommended for better compatibi
90
90
  ```bash
91
91
  npx claude-codex-proxy@latest start
92
92
  ```
93
- The server will start at `http://localhost:8081`.
93
+ The startup prompt asks you to choose **local deployment** or **public deployment**.
94
+
95
+ - Local deployment: no access key is required.
96
+ - Public deployment: enter the UI/admin access key to unlock the Web Dashboard and management APIs. After startup, create and manage Claude Code client API keys from **Settings → Claude Code Client API Keys**.
97
+
98
+ The server will start at `http://localhost:8081` by default. To use another port:
99
+
100
+ ```bash
101
+ PORT=8082 claude-codex-proxy start
102
+ ```
103
+
104
+ PowerShell:
105
+
106
+ ```powershell
107
+ $env:PORT=9000; npm start
108
+ ```
94
109
 
95
110
  ### 2. Add Your Account
96
111
 
@@ -118,15 +133,29 @@ For **headless/VM servers** without a browser:
118
133
  5. Paste it back in the terminal
119
134
 
120
135
  ### 3. Configure Claude Code
121
- Run this command to automatically configure your `claude` CLI to use the proxy:
136
+ Run this command to configure your `claude` CLI to use the proxy:
122
137
  ```bash
123
138
  curl -X POST http://localhost:8081/claude/config/proxy
124
139
  ```
125
140
 
141
+ In local deployment, this writes the local Claude Code configuration on the machine running the proxy.
142
+
143
+ In public deployment, this endpoint does **not** modify the server machine's Claude Code configuration. It only returns the client-side values to set:
144
+ ```json
145
+ {
146
+ "env": {
147
+ "ANTHROPIC_BASE_URL": "http://your-server:8081",
148
+ "ANTHROPIC_API_KEY": "<client-api-key>"
149
+ }
150
+ }
151
+ ```
152
+
153
+ Create a Claude Code client API key in **Settings → Claude Code Client API Keys**, then use it as `ANTHROPIC_API_KEY`.
154
+
126
155
  *Alternatively, set the environment variables manually:*
127
156
  ```bash
128
157
  export ANTHROPIC_BASE_URL=http://localhost:8081
129
- export ANTHROPIC_API_KEY=dummy-key # The key is ignored but required by the CLI
158
+ export ANTHROPIC_API_KEY=<client-api-key>
130
159
  ```
131
160
 
132
161
  To skip Claude Code's login/onboarding prompt, edit `~/.claude.json` and add:
@@ -184,6 +213,7 @@ You can enable it from the Web Dashboard under **Settings → Raw Proxy Payload
184
213
  ```bash
185
214
  curl -X POST http://localhost:8081/settings/raw-proxy-logs \
186
215
  -H "Content-Type: application/json" \
216
+ -H "Authorization: Bearer <ui-admin-key>" \
187
217
  -d '{"enabled":true}'
188
218
  ```
189
219
 
@@ -192,21 +222,24 @@ Disable it again with:
192
222
  ```bash
193
223
  curl -X POST http://localhost:8081/settings/raw-proxy-logs \
194
224
  -H "Content-Type: application/json" \
225
+ -H "Authorization: Bearer <ui-admin-key>" \
195
226
  -d '{"enabled":false}'
196
227
  ```
197
228
 
198
229
  Check the current state:
199
230
 
200
231
  ```bash
201
- curl http://localhost:8081/settings/raw-proxy-logs
232
+ curl http://localhost:8081/settings/raw-proxy-logs \
233
+ -H "Authorization: Bearer <ui-admin-key>"
202
234
  ```
203
235
 
204
236
  Authentication headers and access tokens are not logged.
205
237
 
206
238
  ### API Endpoints
207
239
  - `GET /health`: Check server status.
208
- - `GET /accounts`: List configured accounts.
209
- - `POST /v1/messages`: Anthropic-compatible chat completion endpoint.
240
+ - `GET /accounts`: List configured accounts. In public deployment, requires the UI/admin access key.
241
+ - `POST /v1/messages`: Anthropic-compatible chat completion endpoint. In public deployment, requires the Claude Code client API key.
242
+ - `POST /claude/config/proxy`: Returns Claude Code proxy configuration. In public deployment, this is public and dry-run only.
210
243
 
211
244
  See [API Documentation](./docs/API.md) for full details.
212
245
 
package/bin/cli.js CHANGED
@@ -3,6 +3,8 @@
3
3
  import { fileURLToPath } from 'url';
4
4
  import { dirname, join } from 'path';
5
5
  import { readFileSync } from 'fs';
6
+ import readline from 'readline';
7
+ import { stdin as input, stdout as output } from 'process';
6
8
 
7
9
  const __filename = fileURLToPath(import.meta.url);
8
10
  const __dirname = dirname(__filename);
@@ -68,6 +70,46 @@ function showVersion() {
68
70
  console.log(packageJson.version);
69
71
  }
70
72
 
73
+ function ask(question) {
74
+ const rl = readline.createInterface({ input, output });
75
+ return new Promise((resolve) => {
76
+ rl.question(question, (answer) => {
77
+ rl.close();
78
+ resolve(answer.trim());
79
+ });
80
+ });
81
+ }
82
+
83
+ async function askDeploymentMode() {
84
+ console.log('\nSelect deployment mode:');
85
+ console.log(' 1) Local deployment (no access key required)');
86
+ console.log(' 2) Public deployment (access key required)');
87
+
88
+ while (true) {
89
+ const answer = await ask('Choose mode [1/2]: ');
90
+ if (answer === '1' || /^local$/i.test(answer)) return 'local';
91
+ if (answer === '2' || /^public$/i.test(answer)) return 'public';
92
+ console.log('Please enter 1 for local deployment or 2 for public deployment.');
93
+ }
94
+ }
95
+
96
+ async function askRequiredKey(label) {
97
+ while (true) {
98
+ const apiKey = await ask(`${label}: `);
99
+ if (apiKey) return apiKey;
100
+ console.log('Access key cannot be empty in public deployment mode.');
101
+ }
102
+ }
103
+
104
+ async function configureStartMode() {
105
+ const mode = await askDeploymentMode();
106
+ process.env.PROXY_DEPLOYMENT_MODE = mode;
107
+
108
+ if (mode === 'public') {
109
+ process.env.PROXY_ADMIN_KEY = await askRequiredKey('Enter UI/admin access key');
110
+ }
111
+ }
112
+
71
113
  async function main() {
72
114
  if (args.includes('--help') || args.includes('-h')) {
73
115
  showHelp();
@@ -82,6 +124,7 @@ async function main() {
82
124
  switch (command) {
83
125
  case 'start':
84
126
  case undefined:
127
+ await configureStartMode();
85
128
  await import('../src/index.js');
86
129
  break;
87
130
 
package/docs/API.md CHANGED
@@ -103,6 +103,28 @@ Content-Type: application/json
103
103
  GET /auth/callback?code=...&state=...
104
104
  ```
105
105
 
106
+ ## Client API Key Management
107
+
108
+ In public deployment mode, these endpoints require the UI/admin access key (`Authorization: Bearer <admin-key>`). Key values are returned only from creation responses.
109
+
110
+ | Endpoint | Method | Description |
111
+ |----------|--------|-------------|
112
+ | `/settings/client-api-keys` | GET | List key metadata without key values |
113
+ | `/settings/client-api-keys` | POST | Create a client API key |
114
+ | `/settings/client-api-keys/:id` | PUT | Update name or remark |
115
+ | `/settings/client-api-keys/:id` | DELETE | Revoke and delete the key |
116
+
117
+ ### Create a Client API Key
118
+
119
+ ```bash
120
+ curl -X POST http://localhost:8081/settings/client-api-keys \
121
+ -H "Content-Type: application/json" \
122
+ -H "Authorization: Bearer <admin-key>" \
123
+ -d '{"name":"work-laptop","remark":"primary Claude Code client"}'
124
+ ```
125
+
126
+ Use the `clientApiKey.key` from this one-time response as `ANTHROPIC_API_KEY` for Claude Code.
127
+
106
128
  ## Claude CLI Configuration
107
129
 
108
130
  | Endpoint | Method | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.4",
3
+ "version": "1.0.5-beta.1",
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",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "homepage": "https://github.com/zzy-life/claude-codex-proxy#readme",
31
31
  "scripts": {
32
- "start": "node src/index.js",
32
+ "start": "node bin/cli.js start",
33
33
  "portfolio:dev": "npm --prefix apps/portfolio run dev",
34
34
  "portfolio:build": "npm --prefix apps/portfolio run build",
35
35
  "portfolio:preview": "npm --prefix apps/portfolio run preview",
@@ -47,6 +47,7 @@
47
47
  "test:cors": "node --test tests/cors_security.test.js",
48
48
  "test:ui": "node --test tests/ui.test.js",
49
49
  "pack:check": "npm pack --dry-run",
50
+ "release:beta": "npm run test:unit && npm run pack:check && npm publish --tag beta",
50
51
  "release:npm": "npm run test:unit && npm pack --dry-run && npm publish"
51
52
  },
52
53
  "dependencies": {
package/public/index.html CHANGED
@@ -55,7 +55,26 @@
55
55
  </template>
56
56
  </div>
57
57
 
58
- <div class="h-14 border-b border-space-border flex items-center px-4 lg:px-6 justify-between bg-space-900/50 backdrop-blur-md z-50 relative">
58
+ <div x-show="authChecked && !isAuthenticated" class="min-h-screen flex items-center justify-center px-4">
59
+ <div class="w-full max-w-md bg-space-900/70 border border-space-border rounded-2xl p-6 shadow-2xl backdrop-blur-md">
60
+ <div class="flex items-center gap-3 mb-6">
61
+ <div class="w-10 h-10 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
62
+ <div>
63
+ <h1 class="text-xl font-bold text-white">Access Required</h1>
64
+ <p class="text-sm text-gray-500">Enter the server access key to open the management UI.</p>
65
+ </div>
66
+ </div>
67
+ <form @submit.prevent="login" class="space-y-4">
68
+ <label class="form-control w-full">
69
+ <span class="label-text text-gray-400 mb-1">Access Key</span>
70
+ <input type="password" x-model="loginApiKey" class="input input-bordered w-full bg-space-950 border-space-border text-white" placeholder="Enter access key" autocomplete="current-password">
71
+ </label>
72
+ <button type="submit" class="btn w-full bg-neon-purple hover:bg-purple-600 border-0 text-white">Unlock UI</button>
73
+ </form>
74
+ </div>
75
+ </div>
76
+
77
+ <div x-show="isAuthenticated" class="h-14 border-b border-space-border flex items-center px-4 lg:px-6 justify-between bg-space-900/50 backdrop-blur-md z-50 relative">
59
78
  <div class="flex items-center gap-3">
60
79
  <button @click="sidebarOpen = !sidebarOpen" class="text-gray-400 hover:text-white focus:outline-none p-1 transition-colors lg:hidden">
61
80
  <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@@ -100,10 +119,13 @@
100
119
  <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" />
101
120
  </svg>
102
121
  </button>
122
+
123
+ <button x-show="authRequired" type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white hover:bg-white/5"
124
+ @click="logout()" title="Clear saved access key">Logout</button>
103
125
  </div>
104
126
  </div>
105
127
 
106
- <div class="flex h-[calc(100vh-56px)] relative">
128
+ <div x-show="isAuthenticated" class="flex h-[calc(100vh-56px)] relative">
107
129
  <div x-show="sidebarOpen" x-transition:enter="transition-opacity ease-linear duration-300"
108
130
  x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
109
131
  x-transition:leave="transition-opacity ease-linear duration-300"
@@ -144,6 +166,13 @@
144
166
  </svg>
145
167
  <span>Logs</span>
146
168
  </button>
169
+ <button class="nav-item flex items-center gap-3 px-6 py-3 text-sm font-medium text-gray-400 hover:text-white hover:bg-white/5"
170
+ :class="{'active': activeTab === 'client-api-keys'}" @click="setActiveTab('client-api-keys')">
171
+ <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
172
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2V9a2 2 0 00-2-2h-1V5a5 5 0 00-10 0v2H6a2 2 0 00-2 2v10a2 2 0 002 2z" />
173
+ </svg>
174
+ <span>Client API Keys</span>
175
+ </button>
147
176
  <button class="nav-item flex items-center gap-3 px-6 py-3 text-sm font-medium text-gray-400 hover:text-white hover:bg-white/5"
148
177
  :class="{'active': activeTab === 'settings'}" @click="setActiveTab('settings')">
149
178
  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -256,7 +285,7 @@
256
285
  </div>
257
286
  <div class="bg-space-800/50 border border-space-border/30 rounded-lg p-4 font-mono text-sm text-gray-300">
258
287
  <div class="text-gray-500 mb-2"># Set environment variables</div>
259
- <div class="text-neon-cyan">export ANTHROPIC_BASE_URL=http://localhost:8081</div>
288
+ <div class="text-neon-cyan" x-text="`export ANTHROPIC_BASE_URL=${serverUrl}`"></div>
260
289
  <div class="text-neon-cyan">export ANTHROPIC_API_KEY=any-key</div>
261
290
  <div class="text-gray-500 mt-2 mb-2"># Run Claude</div>
262
291
  <div class="text-neon-green">claude</div>
@@ -265,7 +294,7 @@
265
294
  <div class="mt-4 flex justify-end">
266
295
  <button class="btn btn-sm bg-neon-purple hover:bg-purple-600 border-none text-white font-sans"
267
296
  @click="setClaudeCodeProxyTestConfig()">
268
- Update Claude Code settings.json (localhost:8081 + key=test)
297
+ Update Claude Code settings.json (current server + key=test)
269
298
  </button>
270
299
  </div>
271
300
  </div>
@@ -548,6 +577,53 @@
548
577
  </div>
549
578
  </div>
550
579
 
580
+ <div x-show="activeTab === 'client-api-keys'" x-transition class="view-container">
581
+ <div class="flex flex-wrap items-center justify-between gap-4 mb-6">
582
+ <div class="flex flex-wrap items-center gap-4">
583
+ <h1 class="text-2xl font-bold text-white tracking-tight">Claude Code Client API Keys</h1>
584
+ <div class="flex items-center h-6 px-3 rounded-full bg-space-800/80 border border-space-border/50 shadow-sm backdrop-blur-sm">
585
+ <span class="text-[10px] font-mono text-gray-400 uppercase tracking-wider">Client access management</span>
586
+ </div>
587
+ </div>
588
+ </div>
589
+
590
+ <div class="view-card !p-0 overflow-x-auto">
591
+ <div class="flex items-center justify-between gap-4 px-6 py-4 border-b border-space-border/50">
592
+ <h2 class="text-sm font-semibold text-gray-200">Client API Keys</h2>
593
+ <button class="btn btn-sm bg-neon-purple hover:bg-purple-600 border-none text-white" @click="revealedClientApiKey = ''; showCreateClientApiKeyModal = true">
594
+ New API Key
595
+ </button>
596
+ </div>
597
+ <template x-if="clientApiKeysLoading">
598
+ <div class="text-xs text-gray-500 font-mono py-8 text-center">Loading client API keys...</div>
599
+ </template>
600
+ <table class="w-full min-w-[760px]" x-show="!clientApiKeysLoading && clientApiKeys.length">
601
+ <thead>
602
+ <tr class="bg-space-900/50 border-b border-space-border/50">
603
+ <th class="py-3 pl-6 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Client Name</th>
604
+ <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Remark</th>
605
+ <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Created</th>
606
+ <th class="py-3 pr-6 text-right text-[10px] font-bold text-gray-500 uppercase tracking-wider">Operations</th>
607
+ </tr>
608
+ </thead>
609
+ <tbody>
610
+ <template x-for="clientApiKey in clientApiKeys" :key="clientApiKey.id">
611
+ <tr class="border-b border-space-border/30 last:border-0 hover:bg-white/5 transition-colors">
612
+ <td class="py-3 pl-6"><input type="text" x-model="clientApiKey.name" placeholder="Unnamed" class="input input-sm w-48 bg-space-800 border-space-border text-white"></td>
613
+ <td class="py-3"><input type="text" x-model="clientApiKey.remark" placeholder="No remark" class="input input-sm w-48 bg-space-800 border-space-border text-white"></td>
614
+ <td class="py-3 text-xs font-mono text-gray-500 whitespace-nowrap" x-text="new Date(clientApiKey.createdAt).toLocaleString()"></td>
615
+ <td class="py-3 pr-6"><div class="flex justify-end gap-2 whitespace-nowrap">
616
+ <button class="btn btn-xs btn-outline text-gray-300" @click="updateClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Save</button>
617
+ <button class="btn btn-xs btn-outline text-red-400" @click="deleteClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Delete</button>
618
+ </div></td>
619
+ </tr>
620
+ </template>
621
+ </tbody>
622
+ </table>
623
+ <div x-show="!clientApiKeysLoading && !clientApiKeys.length" class="text-sm text-gray-500 font-mono py-16 text-center">No client API keys. Create one to connect Claude Code clients.</div>
624
+ </div>
625
+ </div>
626
+
551
627
  <div x-show="activeTab === 'settings'" x-transition class="view-container">
552
628
  <div class="flex items-center justify-between gap-4 mb-6">
553
629
  <div class="flex flex-wrap items-center gap-4">
@@ -568,7 +644,7 @@
568
644
  <div class="space-y-3">
569
645
  <div class="flex items-center justify-between py-2 border-b border-space-border/30">
570
646
  <span class="text-sm text-gray-400">Server URL</span>
571
- <span class="font-mono text-sm text-white">http://localhost:8081</span>
647
+ <span class="font-mono text-sm text-white" x-text="serverUrl"></span>
572
648
  </div>
573
649
  <div class="flex items-center justify-between py-2 border-b border-space-border/30">
574
650
  <span class="text-sm text-gray-400">Config Path</span>
@@ -621,19 +697,19 @@
621
697
  <div class="grid gap-3">
622
698
  <div class="grid grid-cols-1 md:grid-cols-[160px_1fr] gap-2 md:items-center">
623
699
  <div>
624
- <div class="text-sm text-gray-300">Claude Sonnet</div>
625
- <div class="text-xs text-gray-500 font-mono">sonnet</div>
700
+ <div class="text-sm text-gray-300">Claude Opus</div>
701
+ <div class="text-xs text-gray-500 font-mono">opus</div>
626
702
  </div>
627
- <input type="text" x-model="modelMappings.sonnet" placeholder="gpt-5.5"
703
+ <input type="text" x-model="modelMappings.opus" placeholder="gpt-5.5"
628
704
  class="input bg-space-800 border-space-border text-white font-mono text-sm">
629
705
  </div>
630
706
 
631
707
  <div class="grid grid-cols-1 md:grid-cols-[160px_1fr] gap-2 md:items-center">
632
708
  <div>
633
- <div class="text-sm text-gray-300">Claude Opus</div>
634
- <div class="text-xs text-gray-500 font-mono">opus</div>
709
+ <div class="text-sm text-gray-300">Claude Sonnet</div>
710
+ <div class="text-xs text-gray-500 font-mono">sonnet</div>
635
711
  </div>
636
- <input type="text" x-model="modelMappings.opus" placeholder="gpt-5.5"
712
+ <input type="text" x-model="modelMappings.sonnet" placeholder="gpt-5.5"
637
713
  class="input bg-space-800 border-space-border text-white font-mono text-sm">
638
714
  </div>
639
715
 
@@ -674,6 +750,45 @@
674
750
  </div>
675
751
  </div>
676
752
 
753
+ <div x-show="showCreateClientApiKeyModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;" @keydown.escape.window="showCreateClientApiKeyModal = false">
754
+ <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="showCreateClientApiKeyModal = false"></div>
755
+ <div class="relative bg-space-900 border border-space-border rounded-xl shadow-2xl max-w-md w-full p-6">
756
+ <h3 class="font-bold text-lg text-white mb-2">New Client API Key</h3>
757
+ <p class="text-sm text-gray-400 mb-5">The key is shown once after creation. Copy it before closing the result.</p>
758
+ <div class="space-y-4">
759
+ <label class="block">
760
+ <span class="block text-xs text-gray-400 mb-2">Name</span>
761
+ <input type="text" x-model="clientApiKeyName" placeholder="e.g. Development workstation"
762
+ class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
763
+ </label>
764
+ <label class="block">
765
+ <span class="block text-xs text-gray-400 mb-2">Remark</span>
766
+ <input type="text" x-model="clientApiKeyRemark" placeholder="Optional note"
767
+ class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
768
+ </label>
769
+ </div>
770
+ <div class="mt-6 flex justify-end gap-2">
771
+ <button class="btn btn-outline btn-sm text-gray-400" @click="showCreateClientApiKeyModal = false" :disabled="clientApiKeySaving">Cancel</button>
772
+ <button class="btn btn-sm bg-neon-purple hover:bg-purple-600 border-none text-white" @click="createClientApiKey()" :disabled="clientApiKeySaving">
773
+ <span x-text="clientApiKeySaving ? 'Creating...' : 'Create Key'"></span>
774
+ </button>
775
+ </div>
776
+ </div>
777
+ </div>
778
+
779
+ <div x-show="revealedClientApiKey" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;" @keydown.escape.window="revealedClientApiKey = ''">
780
+ <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="revealedClientApiKey = ''"></div>
781
+ <div class="relative bg-space-900 border border-yellow-400/40 rounded-xl shadow-2xl max-w-xl w-full p-6">
782
+ <h3 class="font-bold text-lg text-yellow-300 mb-2">Client API Key Created</h3>
783
+ <p class="text-sm text-gray-400 mb-5">Copy this key now. It cannot be retrieved later.</p>
784
+ <code class="block break-all rounded-lg border border-space-border bg-space-800 p-3 text-sm text-white font-mono" x-text="revealedClientApiKey"></code>
785
+ <div class="mt-6 flex justify-end gap-2">
786
+ <button class="btn btn-outline btn-sm text-gray-300" @click="navigator.clipboard.writeText(revealedClientApiKey); showToast('Client API key copied', 'success')">Copy</button>
787
+ <button class="btn btn-sm bg-neon-purple hover:bg-purple-600 border-none text-white" @click="revealedClientApiKey = ''">Done</button>
788
+ </div>
789
+ </div>
790
+ </div>
791
+
677
792
  <div x-show="showAddModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;">
678
793
  <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="showAddModal = false"></div>
679
794
  <div class="relative bg-space-900 border border-space-border rounded-xl shadow-2xl max-w-md w-full p-6">
package/public/js/app.js CHANGED
@@ -8,7 +8,11 @@ document.addEventListener('alpine:init', () => {
8
8
  refreshingTokenEmails: [],
9
9
  toast: null,
10
10
  currentTime: '',
11
-
11
+ authRequired: false,
12
+ authChecked: false,
13
+ apiKey: localStorage.getItem('codexProxyApiKey') || '',
14
+ loginApiKey: '',
15
+
12
16
  accounts: [],
13
17
  searchQuery: '',
14
18
  stats: { total: 0, active: 0, expired: 0, planType: '-' },
@@ -24,6 +28,13 @@ document.addEventListener('alpine:init', () => {
24
28
  strategySaving: false,
25
29
  logRawProxyPayloads: false,
26
30
  rawProxyLogsSaving: false,
31
+ clientApiKeys: [],
32
+ clientApiKeyName: '',
33
+ clientApiKeyRemark: '',
34
+ clientApiKeysLoading: false,
35
+ clientApiKeySaving: false,
36
+ revealedClientApiKey: '',
37
+ showCreateClientApiKeyModal: false,
27
38
 
28
39
  showAddModal: false,
29
40
  showDeleteModal: false,
@@ -41,12 +52,17 @@ document.addEventListener('alpine:init', () => {
41
52
  testing: false,
42
53
 
43
54
  configPath: '~/.claude-codex-proxy/accounts.json',
44
-
55
+ serverUrl: window.location.origin,
56
+
45
57
  logs: [],
46
58
  logSearchQuery: '',
47
59
  logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false },
48
60
  logEventSource: null,
49
61
 
62
+ get isAuthenticated() {
63
+ return !this.authRequired || Boolean(this.apiKey);
64
+ },
65
+
50
66
  get filteredLogs() {
51
67
  const query = this.logSearchQuery.trim().toLowerCase();
52
68
  return this.logs.filter(log => {
@@ -62,16 +78,14 @@ document.addEventListener('alpine:init', () => {
62
78
  return this.accounts.filter(a => a.email.toLowerCase().includes(q));
63
79
  },
64
80
 
65
- init() {
81
+ async init() {
66
82
  this.updateTime();
67
83
  setInterval(() => this.updateTime(), 1000);
68
- this.refreshAccounts();
69
- this.checkHealth();
84
+ await this.checkHealth();
85
+ if (this.isAuthenticated) {
86
+ this.loadProtectedData();
87
+ }
70
88
  setInterval(() => this.checkHealth(), 30000);
71
- this.startLogStream();
72
- this.loadAccountStrategySetting();
73
- this.loadModelMapSetting();
74
- this.loadRawProxyLogsSetting();
75
89
 
76
90
  window.addEventListener('resize', () => {
77
91
  this.sidebarOpen = window.innerWidth >= 1024;
@@ -86,6 +100,15 @@ document.addEventListener('alpine:init', () => {
86
100
  });
87
101
  },
88
102
 
103
+ loadProtectedData() {
104
+ this.refreshAccounts();
105
+ this.startLogStream();
106
+ this.loadAccountStrategySetting();
107
+ this.loadModelMapSetting();
108
+ this.loadRawProxyLogsSetting();
109
+ this.loadClientApiKeys();
110
+ },
111
+
89
112
  updateTime() {
90
113
  this.currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'});
91
114
  },
@@ -99,21 +122,65 @@ document.addEventListener('alpine:init', () => {
99
122
 
100
123
  async api(endpoint, options = {}) {
101
124
  try {
125
+ const headers = {
126
+ 'Content-Type': 'application/json',
127
+ ...(options.headers || {})
128
+ };
129
+
130
+ if (this.apiKey) {
131
+ headers.Authorization = `Bearer ${this.apiKey}`;
132
+ }
133
+
102
134
  const response = await fetch(endpoint, {
103
- headers: { 'Content-Type': 'application/json' },
104
- ...options
135
+ ...options,
136
+ headers
105
137
  });
106
138
  const data = await response.json();
139
+
140
+ if (response.status === 401 && endpoint !== '/health') {
141
+ this.logout(false);
142
+ this.showToast('Access key is invalid or expired', 'error');
143
+ }
144
+
107
145
  return { ok: response.ok, data };
108
146
  } catch (error) {
109
147
  return { ok: false, error: error.message };
110
148
  }
111
149
  },
112
150
 
151
+ login() {
152
+ const key = this.loginApiKey.trim();
153
+ if (!key) {
154
+ this.showToast('Access key is required', 'error');
155
+ return;
156
+ }
157
+
158
+ this.apiKey = key;
159
+ localStorage.setItem('codexProxyApiKey', key);
160
+ this.loginApiKey = '';
161
+ this.showToast('Access key saved', 'success');
162
+ this.loadProtectedData();
163
+ },
164
+
165
+ logout(showMessage = true) {
166
+ this.apiKey = '';
167
+ this.loginApiKey = '';
168
+ localStorage.removeItem('codexProxyApiKey');
169
+ if (this.logEventSource) {
170
+ this.logEventSource.close();
171
+ this.logEventSource = null;
172
+ }
173
+ if (showMessage) this.showToast('Logged out', 'info');
174
+ },
175
+
113
176
  async checkHealth() {
114
177
  const { ok, data } = await this.api('/health');
115
178
  this.connectionStatus = ok ? 'connected' : 'disconnected';
116
179
  if (ok && data?.version) this.version = data.version;
180
+ if (ok && typeof data?.publicMode === 'boolean') {
181
+ this.authRequired = data.publicMode;
182
+ this.authChecked = true;
183
+ }
117
184
  },
118
185
 
119
186
  async refreshAccounts() {
@@ -542,11 +609,75 @@ document.addEventListener('alpine:init', () => {
542
609
  }
543
610
  },
544
611
 
612
+ async loadClientApiKeys() {
613
+ this.clientApiKeysLoading = true;
614
+ const { ok, data } = await this.api('/settings/client-api-keys');
615
+ this.clientApiKeysLoading = false;
616
+ if (ok && Array.isArray(data?.clientApiKeys)) {
617
+ this.clientApiKeys = data.clientApiKeys;
618
+ } else {
619
+ this.showToast(data?.error || 'Failed to load client API keys', 'error');
620
+ }
621
+ },
622
+
623
+ async createClientApiKey() {
624
+ if (this.clientApiKeySaving) return;
625
+ this.clientApiKeySaving = true;
626
+ const { ok, data } = await this.api('/settings/client-api-keys', {
627
+ method: 'POST',
628
+ body: JSON.stringify({
629
+ name: this.clientApiKeyName,
630
+ remark: this.clientApiKeyRemark
631
+ })
632
+ });
633
+ this.clientApiKeySaving = false;
634
+
635
+ if (ok && data?.clientApiKey?.key) {
636
+ this.revealedClientApiKey = data.clientApiKey.key;
637
+ this.clientApiKeyName = '';
638
+ this.clientApiKeyRemark = '';
639
+ this.showCreateClientApiKeyModal = false;
640
+ await this.loadClientApiKeys();
641
+ this.showToast('Client API key created. Copy it now; it will not be shown again.', 'success');
642
+ } else {
643
+ this.showToast(data?.error || 'Failed to create client API key', 'error');
644
+ }
645
+ },
646
+
647
+ async updateClientApiKey(clientApiKey) {
648
+ if (this.clientApiKeySaving) return;
649
+ this.clientApiKeySaving = true;
650
+ const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, {
651
+ method: 'PUT',
652
+ body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark })
653
+ });
654
+ this.clientApiKeySaving = false;
655
+ if (ok) {
656
+ this.showToast('Client API key updated', 'success');
657
+ await this.loadClientApiKeys();
658
+ } else {
659
+ this.showToast(data?.error || 'Failed to update client API key', 'error');
660
+ }
661
+ },
662
+
663
+ async deleteClientApiKey(clientApiKey) {
664
+ if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return;
665
+ this.clientApiKeySaving = true;
666
+ const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' });
667
+ this.clientApiKeySaving = false;
668
+ if (ok) {
669
+ await this.loadClientApiKeys();
670
+ this.showToast('Client API key deleted', 'success');
671
+ } else {
672
+ this.showToast(data?.error || 'Failed to delete client API key', 'error');
673
+ }
674
+ },
675
+
545
676
  async setClaudeCodeProxyTestConfig() {
546
677
  const { ok, data, error } = await this.api('/claude/config/set', {
547
678
  method: 'POST',
548
679
  body: JSON.stringify({
549
- apiUrl: 'http://localhost:8081',
680
+ apiUrl: this.serverUrl,
550
681
  apiKey: 'test'
551
682
  })
552
683
  });
@@ -564,9 +695,12 @@ document.addEventListener('alpine:init', () => {
564
695
  },
565
696
 
566
697
  startLogStream() {
698
+ if (!this.isAuthenticated) return;
567
699
  if (this.logEventSource) this.logEventSource.close();
568
-
569
- this.logEventSource = new EventSource('/api/logs/stream?history=true');
700
+
701
+ const params = new URLSearchParams({ history: 'true' });
702
+ if (this.apiKey) params.set('api_key', this.apiKey);
703
+ this.logEventSource = new EventSource(`/api/logs/stream?${params.toString()}`);
570
704
  this.logEventSource.onmessage = (event) => {
571
705
  try {
572
706
  const log = JSON.parse(event.data);