vtcode-auth 0.98.4

Authentication and OAuth flows shared across VT Code
Documentation
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
use anyhow::{Context, Result};
use axum::{
    Router,
    extract::{Query, State},
    response::Html,
    routing::get,
};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};

const DEFAULT_CALLBACK_TIMEOUT_SECS: u64 = 300;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum OAuthProvider {
    OpenAi,
    OpenRouter,
}

impl OAuthProvider {
    #[must_use]
    pub fn slug(self) -> &'static str {
        match self {
            Self::OpenAi => "openai",
            Self::OpenRouter => "openrouter",
        }
    }

    #[must_use]
    pub fn display_name(self) -> &'static str {
        match self {
            Self::OpenAi => "OpenAI",
            Self::OpenRouter => "OpenRouter",
        }
    }

    #[must_use]
    pub fn subtitle(self) -> &'static str {
        match self {
            Self::OpenAi => "Your ChatGPT subscription is now connected.",
            Self::OpenRouter => "Your OpenRouter account is now connected.",
        }
    }

    #[must_use]
    pub fn failure_subtitle(self) -> &'static str {
        match self {
            Self::OpenAi => "Unable to connect your ChatGPT subscription.",
            Self::OpenRouter => "Unable to connect your OpenRouter account.",
        }
    }

    #[must_use]
    pub fn retry_hint(self) -> String {
        format!("You can try again anytime using /login {}", self.slug())
    }

    #[must_use]
    pub fn supports_manual_refresh(self) -> bool {
        matches!(self, Self::OpenAi)
    }
}

impl fmt::Display for OAuthProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.slug())
    }
}

impl FromStr for OAuthProvider {
    type Err = ();

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "openai" => Ok(Self::OpenAi),
            "openrouter" => Ok(Self::OpenRouter),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct OAuthCallbackPage {
    provider_slug: &'static str,
    success_subtitle: &'static str,
    failure_subtitle: &'static str,
    retry_hint: &'static str,
}

impl OAuthCallbackPage {
    #[must_use]
    pub fn new(provider: OAuthProvider) -> Self {
        match provider {
            OAuthProvider::OpenAi => Self {
                provider_slug: "openai",
                success_subtitle: "Your ChatGPT subscription is now connected.",
                failure_subtitle: "Unable to connect your ChatGPT subscription.",
                retry_hint: "You can try again anytime using /login openai",
            },
            OAuthProvider::OpenRouter => Self {
                provider_slug: "openrouter",
                success_subtitle: "Your OpenRouter account is now connected.",
                failure_subtitle: "Unable to connect your OpenRouter account.",
                retry_hint: "You can try again anytime using /login openrouter",
            },
        }
    }

    #[must_use]
    pub fn custom(
        provider_slug: &'static str,
        success_subtitle: &'static str,
        failure_subtitle: &'static str,
        retry_hint: &'static str,
    ) -> Self {
        Self {
            provider_slug,
            success_subtitle,
            failure_subtitle,
            retry_hint,
        }
    }

    #[must_use]
    pub fn provider_slug(&self) -> &'static str {
        self.provider_slug
    }

    #[must_use]
    pub fn success_subtitle(&self) -> &'static str {
        self.success_subtitle
    }

    #[must_use]
    pub fn failure_subtitle(&self) -> &'static str {
        self.failure_subtitle
    }

    #[must_use]
    pub fn retry_hint(&self) -> &'static str {
        self.retry_hint
    }
}

#[derive(Debug, Clone)]
pub enum AuthCallbackOutcome {
    Code(String),
    Cancelled,
    Error(String),
}

pub struct AuthCodeCallbackServer {
    timeout: Duration,
    result_rx: mpsc::Receiver<AuthCallbackOutcome>,
    shutdown_tx: Option<oneshot::Sender<()>>,
    server_handle: Option<tokio::task::JoinHandle<()>>,
}

impl AuthCodeCallbackServer {
    pub async fn start(
        port: u16,
        timeout_secs: u64,
        page: OAuthCallbackPage,
        expected_state: Option<String>,
    ) -> Result<Self> {
        let (result_tx, result_rx) = mpsc::channel::<AuthCallbackOutcome>(1);
        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
        let state = Arc::new(AuthCallbackState {
            page,
            expected_state,
            result_tx,
        });

        let app = Router::new()
            .route("/callback", get(handle_callback))
            .route("/auth/callback", get(handle_callback))
            .route("/cancel", get(handle_cancel))
            .route("/health", get(|| async { "OK" }))
            .with_state(state);

        let addr = SocketAddr::from(([127, 0, 0, 1], port));
        let listener = tokio::net::TcpListener::bind(addr)
            .await
            .with_context(|| format!("failed to bind localhost callback server on port {port}"))?;

        let server = axum::serve(listener, app).with_graceful_shutdown(async move {
            let _ = shutdown_rx.await;
        });
        let server_handle = tokio::spawn(async move {
            if let Err(err) = server.await {
                tracing::error!("OAuth callback server error: {}", err);
            }
        });

        Ok(Self {
            timeout: callback_timeout(timeout_secs),
            result_rx,
            shutdown_tx: Some(shutdown_tx),
            server_handle: Some(server_handle),
        })
    }

    pub async fn wait(mut self) -> Result<AuthCallbackOutcome> {
        let result = tokio::select! {
            Some(result) = self.result_rx.recv() => result,
            _ = tokio::time::sleep(self.timeout) => {
                AuthCallbackOutcome::Error(format!(
                    "OAuth flow timed out after {} seconds",
                    self.timeout.as_secs()
                ))
            }
        };

        self.shutdown().await;
        Ok(result)
    }

    async fn shutdown(&mut self) {
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }
        if let Some(server_handle) = self.server_handle.take() {
            let _ = server_handle.await;
        }
    }
}

impl Drop for AuthCodeCallbackServer {
    fn drop(&mut self) {
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }
        if let Some(server_handle) = self.server_handle.take() {
            server_handle.abort();
        }
    }
}

#[derive(Debug, Deserialize)]
struct AuthCallbackParams {
    code: Option<String>,
    error: Option<String>,
    error_description: Option<String>,
    state: Option<String>,
}

struct AuthCallbackState {
    page: OAuthCallbackPage,
    expected_state: Option<String>,
    result_tx: mpsc::Sender<AuthCallbackOutcome>,
}

pub async fn start_auth_code_callback_server(
    port: u16,
    timeout_secs: u64,
    page: OAuthCallbackPage,
    expected_state: Option<String>,
) -> Result<AuthCodeCallbackServer> {
    AuthCodeCallbackServer::start(port, timeout_secs, page, expected_state).await
}

pub async fn run_auth_code_callback_server(
    port: u16,
    timeout_secs: u64,
    page: OAuthCallbackPage,
    expected_state: Option<String>,
) -> Result<AuthCallbackOutcome> {
    start_auth_code_callback_server(port, timeout_secs, page, expected_state)
        .await?
        .wait()
        .await
}

async fn handle_callback(
    State(state): State<Arc<AuthCallbackState>>,
    Query(params): Query<AuthCallbackParams>,
) -> Html<String> {
    tracing::info!(
        provider = state.page.provider_slug(),
        has_code = params.code.is_some(),
        has_error = params.error.is_some(),
        "received oauth callback"
    );
    if let Some(expected_state) = state.expected_state.as_deref() {
        match params.state.as_deref() {
            Some(actual_state) if actual_state == expected_state => {}
            _ => {
                let message = "OAuth error: state mismatch".to_string();
                let _ = state
                    .result_tx
                    .send(AuthCallbackOutcome::Error(message.clone()))
                    .await;
                return Html(error_html(state.page, &message));
            }
        }
    }

    if let Some(error) = params.error {
        let message = match params.error_description {
            Some(description) if !description.trim().is_empty() => {
                format!("OAuth error: {error} - {description}")
            }
            _ => format!("OAuth error: {error}"),
        };
        let _ = state
            .result_tx
            .send(AuthCallbackOutcome::Error(message.clone()))
            .await;
        return Html(error_html(state.page, &message));
    }

    let Some(code) = params.code else {
        let message = "Missing authorization code".to_string();
        let _ = state
            .result_tx
            .send(AuthCallbackOutcome::Error(message.clone()))
            .await;
        return Html(error_html(state.page, &message));
    };

    let _ = state.result_tx.send(AuthCallbackOutcome::Code(code)).await;
    Html(success_html(state.page))
}

async fn handle_cancel(State(state): State<Arc<AuthCallbackState>>) -> Html<String> {
    let _ = state.result_tx.send(AuthCallbackOutcome::Cancelled).await;
    Html(cancelled_html(state.page))
}

fn success_html(page: OAuthCallbackPage) -> String {
    base_html(
        "Authentication Successful",
        page.success_subtitle(),
        Some("You may now close this window and return to VT Code."),
        "✓",
        "#22c55e",
        None,
    )
}

fn error_html(page: OAuthCallbackPage, error: &str) -> String {
    base_html(
        "Authentication Failed",
        page.failure_subtitle(),
        None,
        "✕",
        "#ef4444",
        Some(error),
    )
}

fn cancelled_html(page: OAuthCallbackPage) -> String {
    base_html(
        "Authentication Cancelled",
        page.retry_hint(),
        None,
        "—",
        "#71717a",
        None,
    )
}

fn base_html(
    title: &str,
    subtitle: &str,
    close_note: Option<&str>,
    icon: &str,
    accent: &str,
    error: Option<&str>,
) -> String {
    let close_note_html = close_note
        .map(|value| format!(r#"<p class="close-note">{}</p>"#, html_escape(value)))
        .unwrap_or_default();
    let error_html = error
        .map(|value| format!(r#"<div class="error">{}</div>"#, html_escape(value)))
        .unwrap_or_default();
    let auto_close = if close_note.is_some() {
        r#"<script>setTimeout(() => window.close(), 3000);</script>"#
    } else {
        ""
    };

    format!(
        r##"<!DOCTYPE html>
<html>
<head>
    <title>VT Code - {title}</title>
    <style>
        @font-face {{
            font-family: 'SF Pro Display';
            src: local('SF Pro Display'), local('.SF NS Display'), local('Helvetica Neue');
        }}
        @font-face {{
            font-family: 'SF Mono';
            src: local('SF Mono'), local('Menlo'), local('Monaco');
        }}
        :root {{
            color-scheme: dark;
            --bg: #0a0a0a;
            --panel: #111111;
            --panel-border: #262626;
            --text: #fafafa;
            --muted: #a1a1aa;
            --subtle: #52525b;
            --code-bg: #18181b;
            --code-border: #27272a;
            --accent: {accent};
        }}
        * {{ box-sizing: border-box; }}
        body {{
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background:
                radial-gradient(circle at top, rgba(255,255,255,0.04), transparent 32%),
                linear-gradient(180deg, var(--bg), #050505);
            color: var(--text);
            padding: 24px;
        }}
        .container {{
            text-align: center;
            padding: 2.75rem 3rem;
            border: 1px solid var(--panel-border);
            border-radius: 14px;
            background: rgba(17, 17, 17, 0.92);
            max-width: 460px;
            width: 100%;
            box-shadow: 0 30px 90px rgba(0, 0, 0, 0.35);
        }}
        .logo {{
            margin-bottom: 1.5rem;
        }}
        .logo-mark {{
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 0.95rem;
            letter-spacing: 0.24em;
            text-transform: uppercase;
            color: var(--muted);
        }}
        .status-icon {{
            width: 52px;
            height: 52px;
            margin: 0 auto 1.25rem;
            border: 2px solid var(--accent);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            color: var(--accent);
        }}
        h1 {{
            margin: 0 0 0.75rem 0;
            font-size: 1.25rem;
            font-weight: 600;
            letter-spacing: -0.02em;
        }}
        p {{
            color: var(--muted);
            margin: 0;
            font-size: 0.92rem;
            line-height: 1.55;
        }}
        .close-note {{
            margin-top: 1.25rem;
            font-size: 0.78rem;
            color: var(--subtle);
        }}
        .error {{
            margin-top: 1.35rem;
            padding: 0.95rem 1rem;
            background: var(--code-bg);
            border: 1px solid var(--code-border);
            border-radius: 10px;
            font-family: 'SF Mono', Menlo, Monaco, monospace;
            font-size: 0.75rem;
            color: #d4d4d8;
            word-break: break-word;
            text-align: left;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <div class="logo-mark">&gt; VT Code</div>
        </div>
        <div class="status-icon">{icon}</div>
        <h1>{title}</h1>
        <p>{subtitle}</p>
        {close_note_html}
        {error_html}
    </div>
    {auto_close}
</body>
</html>"##,
        title = html_escape(title),
        subtitle = html_escape(subtitle),
        icon = icon,
        accent = accent,
        close_note_html = close_note_html,
        error_html = error_html,
        auto_close = auto_close,
    )
}

fn html_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

fn callback_timeout(timeout_secs: u64) -> Duration {
    Duration::from_secs(if timeout_secs == 0 {
        DEFAULT_CALLBACK_TIMEOUT_SECS
    } else {
        timeout_secs
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::extract::{Query, State};
    use reqwest::Client;

    #[test]
    fn oauth_provider_parses_known_providers() {
        assert_eq!("openai".parse::<OAuthProvider>(), Ok(OAuthProvider::OpenAi));
        assert_eq!(
            "openrouter".parse::<OAuthProvider>(),
            Ok(OAuthProvider::OpenRouter)
        );
        assert!("other".parse::<OAuthProvider>().is_err());
    }

    #[test]
    fn success_html_mentions_vtcode_and_autoclose() {
        let html = success_html(OAuthCallbackPage::new(OAuthProvider::OpenAi));
        assert!(html.contains("VT Code"));
        assert!(html.contains("Authentication Successful"));
        assert!(html.contains("window.close"));
    }

    #[tokio::test]
    async fn callback_rejects_state_mismatch() {
        let (result_tx, mut result_rx) = mpsc::channel(1);
        let state = Arc::new(AuthCallbackState {
            page: OAuthCallbackPage::new(OAuthProvider::OpenAi),
            expected_state: Some("expected-state".to_string()),
            result_tx,
        });

        let html = handle_callback(
            State(state),
            Query(AuthCallbackParams {
                code: Some("auth-code".to_string()),
                error: None,
                error_description: None,
                state: Some("wrong-state".to_string()),
            }),
        )
        .await;

        let outcome = result_rx.recv().await.expect("callback outcome");
        match outcome {
            AuthCallbackOutcome::Error(message) => {
                assert!(message.contains("state mismatch"));
            }
            _ => panic!("expected error outcome"),
        }
        assert!(html.0.contains("Authentication Failed"));
    }

    #[tokio::test]
    async fn callback_server_starts_listening_before_wait() {
        let listener = match std::net::TcpListener::bind(("127.0.0.1", 0)) {
            Ok(listener) => listener,
            Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return,
            Err(err) => panic!("bind temp port: {err}"),
        };
        let port = listener.local_addr().expect("local addr").port();
        drop(listener);

        let server = start_auth_code_callback_server(
            port,
            5,
            OAuthCallbackPage::new(OAuthProvider::OpenAi),
            None,
        )
        .await
        .expect("start callback server");
        let client = Client::builder()
            .no_proxy()
            .build()
            .expect("build http client");

        let health = client
            .get(format!("http://127.0.0.1:{port}/health"))
            .send()
            .await
            .expect("health request should succeed");
        assert!(health.status().is_success());

        let cancel = client
            .get(format!("http://127.0.0.1:{port}/cancel"))
            .send()
            .await
            .expect("cancel request should succeed");
        assert!(cancel.status().is_success());

        assert!(matches!(
            server.wait().await.expect("wait for callback outcome"),
            AuthCallbackOutcome::Cancelled
        ));
    }
}