claude-code-mux 0.5.2

High-performance, intelligent Claude Code router built in Rust
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
use axum::{
    extract::{Query, State},
    http::StatusCode,
    response::{Html, IntoResponse},
    Json,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use crate::auth::{OAuthClient, OAuthConfig, TokenStore};

use super::AppState;

/// Request to start OAuth authorization flow
#[derive(Debug, Deserialize)]
pub struct OAuthAuthorizeRequest {
    /// Type of OAuth flow: "max" (Claude Pro/Max) or "console" (API key creation)
    #[serde(default = "default_oauth_type")]
    pub oauth_type: String,
}

fn default_oauth_type() -> String {
    "max".to_string()
}

/// Response with authorization URL
#[derive(Debug, Serialize)]
pub struct OAuthAuthorizeResponse {
    /// Authorization URL for user to visit
    pub url: String,
    /// PKCE verifier (store this for exchange step)
    pub verifier: String,
    /// Instructions for the user
    pub instructions: String,
}

/// Request to exchange authorization code for tokens
#[derive(Debug, Deserialize)]
pub struct OAuthExchangeRequest {
    /// Authorization code from OAuth callback
    pub code: String,
    /// PKCE verifier from authorize step
    pub verifier: String,
    /// Provider ID to store token under
    pub provider_id: String,
    /// OAuth type (optional, for determining config)
    #[serde(default)]
    pub oauth_type: Option<String>,
}

/// Response after successful token exchange
#[derive(Debug, Serialize)]
pub struct OAuthExchangeResponse {
    /// Success status
    pub success: bool,
    /// Message
    pub message: String,
    /// Provider ID
    pub provider_id: String,
    /// Token expiration timestamp (ISO 8601)
    pub expires_at: String,
}

/// Token information for listing
#[derive(Debug, Serialize)]
pub struct TokenInfo {
    pub provider_id: String,
    pub expires_at: String,
    pub is_expired: bool,
    pub needs_refresh: bool,
}

/// Get authorization URL
pub async fn oauth_authorize(
    State(state): State<Arc<AppState>>,
    Json(req): Json<OAuthAuthorizeRequest>,
) -> Result<Json<OAuthAuthorizeResponse>, (StatusCode, String)> {
    // Create OAuth config based on type
    let config = match req.oauth_type.as_str() {
        "max" => OAuthConfig::anthropic(),
        "console" => OAuthConfig::anthropic_console(),
        "openai-codex" => OAuthConfig::openai_codex(),
        _ => return Err((
            StatusCode::BAD_REQUEST,
            "Invalid oauth_type. Must be 'max', 'console', or 'openai-codex'".to_string()
        )),
    };

    let oauth_client = OAuthClient::new(config, state.token_store.clone());
    let auth_url = oauth_client.get_authorization_url();

    let instructions = match req.oauth_type.as_str() {
        "max" => "Visit the URL above to authorize with your Claude Pro/Max account. After authorization, you'll receive a code. Paste it in the next step.".to_string(),
        "console" => "Visit the URL above to authorize and create an API key. After authorization, you'll receive a code. Paste it in the next step.".to_string(),
        "openai-codex" => "Visit the URL above to authorize with your ChatGPT Plus/Pro account. After authorization, you'll receive a code. Paste it in the next step.".to_string(),
        _ => String::new(),
    };

    Ok(Json(OAuthAuthorizeResponse {
        url: auth_url.url,
        verifier: auth_url.verifier.verifier,
        instructions,
    }))
}

/// Exchange authorization code for tokens
pub async fn oauth_exchange(
    State(state): State<Arc<AppState>>,
    Json(req): Json<OAuthExchangeRequest>,
) -> Result<Json<OAuthExchangeResponse>, (StatusCode, String)> {
    // Determine OAuth config based on oauth_type if provided, otherwise fall back to provider_id
    let config = if let Some(ref oauth_type) = req.oauth_type {
        match oauth_type.as_str() {
            "openai-codex" => OAuthConfig::openai_codex(),
            "console" => OAuthConfig::anthropic_console(),
            "max" => OAuthConfig::anthropic(),
            _ => return Err((
                StatusCode::BAD_REQUEST,
                format!("Invalid oauth_type: {}", oauth_type)
            )),
        }
    } else if req.provider_id.to_lowercase().contains("openai") ||
              req.provider_id.to_lowercase().contains("codex") ||
              req.provider_id.to_lowercase().contains("chatgpt") {
        OAuthConfig::openai_codex()
    } else {
        OAuthConfig::anthropic()
    };

    let oauth_client = OAuthClient::new(config, state.token_store.clone());

    // Exchange code for tokens
    let token = oauth_client
        .exchange_code(&req.code, &req.verifier, &req.provider_id)
        .await
        .map_err(|e| (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to exchange code: {}", e)
        ))?;

    Ok(Json(OAuthExchangeResponse {
        success: true,
        message: "OAuth authentication successful! Token saved.".to_string(),
        provider_id: req.provider_id,
        expires_at: token.expires_at.to_rfc3339(),
    }))
}

/// List all OAuth tokens
pub async fn oauth_list_tokens(
    State(state): State<Arc<AppState>>,
) -> Result<Json<Vec<TokenInfo>>, (StatusCode, String)> {
    let all_tokens = state.token_store.all();

    let token_infos: Vec<TokenInfo> = all_tokens
        .into_iter()
        .map(|(_, token)| TokenInfo {
            provider_id: token.provider_id.clone(),
            expires_at: token.expires_at.to_rfc3339(),
            is_expired: token.is_expired(),
            needs_refresh: token.needs_refresh(),
        })
        .collect();

    Ok(Json(token_infos))
}

/// Delete OAuth token
#[derive(Debug, Deserialize)]
pub struct DeleteTokenRequest {
    pub provider_id: String,
}

pub async fn oauth_delete_token(
    State(state): State<Arc<AppState>>,
    Json(req): Json<DeleteTokenRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    state.token_store
        .remove(&req.provider_id)
        .map_err(|e| (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to delete token: {}", e)
        ))?;

    Ok(Json(serde_json::json!({
        "success": true,
        "message": format!("Token for '{}' deleted", req.provider_id),
    })))
}

/// Refresh a token manually (for testing/debugging)
pub async fn oauth_refresh_token(
    State(state): State<Arc<AppState>>,
    Json(req): Json<DeleteTokenRequest>,
) -> Result<Json<OAuthExchangeResponse>, (StatusCode, String)> {
    // Determine OAuth config based on provider_id (check for OpenAI keywords)
    let config = if req.provider_id.to_lowercase().contains("openai") ||
                     req.provider_id.to_lowercase().contains("codex") ||
                     req.provider_id.to_lowercase().contains("chatgpt") {
        OAuthConfig::openai_codex()
    } else {
        OAuthConfig::anthropic()
    };

    let oauth_client = OAuthClient::new(config, state.token_store.clone());

    let token = oauth_client
        .refresh_token(&req.provider_id)
        .await
        .map_err(|e| (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to refresh token: {}", e)
        ))?;

    Ok(Json(OAuthExchangeResponse {
        success: true,
        message: "Token refreshed successfully".to_string(),
        provider_id: req.provider_id,
        expires_at: token.expires_at.to_rfc3339(),
    }))
}

/// OAuth callback query parameters
#[derive(Debug, Deserialize)]
pub struct OAuthCallbackQuery {
    pub code: Option<String>,
    pub state: Option<String>,
    pub error: Option<String>,
    pub error_description: Option<String>,
}

/// OAuth callback handler - displays the authorization code to the user
pub async fn oauth_callback(
    Query(params): Query<OAuthCallbackQuery>,
) -> Html<String> {
    // Check for errors
    if let Some(error) = params.error {
        let error_desc = params.error_description.unwrap_or_else(|| "Unknown error".to_string());
        return Html(format!(r#"
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OAuth Error</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }}
        .container {{
            background: white;
            padding: 3rem;
            border-radius: 1rem;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 500px;
            text-align: center;
        }}
        .error-icon {{
            font-size: 4rem;
            margin-bottom: 1rem;
        }}
        h1 {{
            color: #e53e3e;
            margin-bottom: 1rem;
        }}
        .error-message {{
            background: #fff5f5;
            border: 1px solid #feb2b2;
            color: #c53030;
            padding: 1rem;
            border-radius: 0.5rem;
            margin-top: 1rem;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="error-icon">❌</div>
        <h1>Authorization Failed</h1>
        <p><strong>Error:</strong> {error}</p>
        <div class="error-message">{error_desc}</div>
        <p style="margin-top: 2rem; color: #666;">You can close this window and try again.</p>
    </div>
</body>
</html>
"#));
    }

    // Extract code (state is not used for token exchange, verifier is stored in frontend)
    let code = params.code.unwrap_or_else(|| "No code received".to_string());

    Html(format!(r#"
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Authorization Successful</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }}
        .container {{
            background: white;
            padding: 3rem;
            border-radius: 1rem;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 500px;
            text-align: center;
        }}
        .success-icon {{
            font-size: 4rem;
            margin-bottom: 1rem;
        }}
        h1 {{
            color: #2d3748;
            margin-bottom: 1rem;
        }}
        .code-box {{
            background: #f7fafc;
            border: 2px solid #e2e8f0;
            padding: 1.5rem;
            border-radius: 0.5rem;
            margin: 1.5rem 0;
            position: relative;
        }}
        .code {{
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            word-break: break-all;
            color: #2d3748;
            user-select: all;
        }}
        .copy-button {{
            margin-top: 1rem;
            background: #667eea;
            color: white;
            border: none;
            padding: 0.75rem 2rem;
            border-radius: 0.5rem;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.3s;
        }}
        .copy-button:hover {{
            background: #5a67d8;
        }}
        .copy-button:active {{
            background: #4c51bf;
        }}
        .copied {{
            color: #48bb78;
            font-weight: bold;
            margin-top: 0.5rem;
            opacity: 0;
            transition: opacity 0.3s;
        }}
        .copied.show {{
            opacity: 1;
        }}
        .instructions {{
            text-align: left;
            margin-top: 2rem;
            padding: 1rem;
            background: #edf2f7;
            border-radius: 0.5rem;
        }}
        .instructions ol {{
            margin: 0.5rem 0;
            padding-left: 1.5rem;
        }}
        .instructions li {{
            margin: 0.5rem 0;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="success-icon">✅</div>
        <h1>Authorization Successful!</h1>
        <p>Copy the code below and paste it in the admin panel:</p>

        <div class="code-box">
            <div class="code" id="authCode">{code}</div>
        </div>
        
        <button class="copy-button" onclick="copyCode()">📋 Copy Code</button>
        <div class="copied" id="copiedMsg">✓ Copied to clipboard!</div>
        
        <div class="instructions">
            <strong>Next steps:</strong>
            <ol>
                <li>Click "Copy Code" button above</li>
                <li>Return to the admin panel</li>
                <li>Paste the code in the authorization field</li>
                <li>Click "Complete OAuth" to finish</li>
            </ol>
        </div>
        
        <p style="margin-top: 2rem; color: #666;">You can close this window after copying the code.</p>
    </div>

    <script>
        function copyCode() {{
            const codeText = document.getElementById('authCode').textContent;
            navigator.clipboard.writeText(codeText).then(() => {{
                const copiedMsg = document.getElementById('copiedMsg');
                copiedMsg.classList.add('show');
                setTimeout(() => {{
                    copiedMsg.classList.remove('show');
                }}, 2000);
            }});
        }}
        
        // Auto-select code on click
        document.getElementById('authCode').addEventListener('click', function() {{
            const range = document.createRange();
            range.selectNodeContents(this);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
        }});
    </script>
</body>
</html>
"#))
}