cinchdb 0.2.4

CLI for CinchDB - database and scope management
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
//! Authentication commands: login, logout, whoami, api-keys

use crate::client::ApiClient;
use crate::config::ConfigFile;
use crate::output;
use anyhow::{Context, Result};
use clap::Subcommand;
use serde::{Deserialize, Serialize};
use std::io::Write;

#[derive(Subcommand)]
pub enum AuthCommands {
    /// Log in to CinchDB (opens browser, or --headless for CI)
    Login {
        /// Use headless mode (paste API key instead of browser)
        #[arg(long)]
        headless: bool,
    },
    /// Log out and clear stored credentials
    Logout,
    /// Show current user and context
    Whoami,
    /// Manage API keys
    ApiKeys {
        #[command(subcommand)]
        command: ApiKeyCommands,
    },
}

#[derive(Subcommand)]
pub enum ApiKeyCommands {
    /// Create a new API key
    Create {
        /// Key description
        #[arg(long)]
        name: Option<String>,
    },
    /// List API keys
    List,
    /// Revoke an API key
    Revoke {
        /// Key ID or prefix
        key_id: String,
    },
}

pub async fn run(command: AuthCommands, api_url: &str, json: bool) -> Result<()> {
    match command {
        AuthCommands::Login { headless } => {
            if headless {
                login_headless(api_url).await
            } else {
                login_browser(api_url).await
            }
        }
        AuthCommands::Logout => logout(api_url, json).await,
        AuthCommands::Whoami => whoami(api_url, json).await,
        AuthCommands::ApiKeys { command } => api_keys(command, api_url, json).await,
    }
}

/// Browser-based OAuth login flow:
/// 1. Start a local HTTP server on a random port
/// 2. Open the browser to the dashboard login with a callback to localhost
/// 3. Dashboard redirects to localhost with the JWT token
/// 4. CLI captures the token and stores it in config
async fn login_browser(api_url: &str) -> Result<()> {
    // Check if already logged in
    let config = ConfigFile::load()?;
    if config.auth.token.is_some() || config.auth.api_key.is_some() {
        println!("Already logged in. Use `cinch auth logout` first to switch accounts.");
        return Ok(());
    }

    // Bind a local server on a random port
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .context("failed to bind local callback server")?;
    let port = listener
        .local_addr()
        .context("failed to get local address")?
        .port();

    // Open the dashboard's CLI auth page. The dashboard handles login (GitHub/magic link)
    // and redirects the JWT to our localhost callback after auth completes.
    let callback_url = format!("http://127.0.0.1:{port}/callback");
    let dashboard_url = resolve_dashboard_url(api_url);
    let login_url = format!(
        "{dashboard_url}/auth/cli/?callback={}",
        urlencoding::encode(&callback_url)
    );

    println!("Opening browser to log in...");
    println!();
    println!("  If the browser doesn't open, visit:");
    println!("  {login_url}");
    println!();

    if let Err(e) = open::that(&login_url) {
        eprintln!("  Could not open browser automatically: {e}");
        eprintln!("  Please visit the URL above manually.");
    }

    println!("Waiting for authentication...");

    // Accept one connection and extract the token from the callback
    let token = accept_callback(listener).await?;

    // Store the token
    let mut config = ConfigFile::load()?;
    config.auth.token = Some(token);
    config.save()?;

    // Fetch user info to confirm and set org context
    let client = ApiClient::new(api_url)?;
    let user: UserInfo = client
        .get("/users/me")
        .await
        .context("login succeeded but failed to fetch user info")?;

    println!();
    output::print_success(
        &format!("Logged in as {}", user.email),
        Some("cinch db create mydb --type redis"),
    );

    // Auto-set org context if user has exactly one org
    if let Ok(orgs) = client.get::<UserOrgsResponse>("/users/me/orgs").await {
        if orgs.organizations.len() == 1 {
            let org = &orgs.organizations[0];
            config.context.org = Some(org.slug.clone());
            config.save()?;
            println!("  Set org context to \"{}\"", org.slug);
        }
    }

    Ok(())
}

/// Accept the OAuth callback on the local server and extract the JWT token
async fn accept_callback(listener: tokio::net::TcpListener) -> Result<String> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let (mut stream, _) = listener
        .accept()
        .await
        .context("failed to accept callback connection")?;

    let mut buf = vec![0u8; 4096];
    let n = stream
        .read(&mut buf)
        .await
        .context("failed to read callback request")?;
    let request = String::from_utf8_lossy(&buf[..n]);

    // Parse the GET request to extract the token
    // Expected: GET /callback?token=<jwt> HTTP/1.1
    let token = request
        .lines()
        .next()
        .and_then(|line| {
            let path = line.split_whitespace().nth(1)?;
            let query = path.split('?').nth(1)?;
            query
                .split('&')
                .find_map(|param| param.strip_prefix("token="))
        })
        .map(|t| t.to_string())
        .context("callback did not contain a token parameter")?;

    // Send a friendly HTML response
    let html = r#"<!DOCTYPE html>
<html>
<head><title>CinchDB CLI</title></head>
<body style="font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;">
<div style="text-align: center;">
<h1>Logged in!</h1>
<p>You can close this tab and return to your terminal.</p>
</div>
</body>
</html>"#;

    let response = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
        html.len(),
        html
    );
    // Best-effort: browser may close connection before we respond.
    // Token is already captured, so write failure is cosmetic only.
    let _ = stream.write_all(response.as_bytes()).await;
    let _ = stream.shutdown().await;

    Ok(token)
}

/// Derive the dashboard URL from the API URL.
/// api.cinchdb.dev -> app.cinchdb.dev
/// localhost:8080 -> localhost:5200 (local dev)
fn resolve_dashboard_url(api_url: &str) -> String {
    if let Ok(url) = std::env::var("CINCH_DASHBOARD_URL") {
        return url;
    }
    // Local development: API on 8080, dashboard on 5200
    if api_url.contains("localhost") || api_url.contains("127.0.0.1") {
        return api_url
            .replace(":8080", ":5200")
            .replace(":8081", ":5200");
    }
    // Production/staging: api.X -> app.X
    api_url
        .replace("://api.", "://app.")
        .replace("://api-", "://app-")
}

/// Headless login: user pastes an API key
async fn login_headless(api_url: &str) -> Result<()> {
    println!("Headless login: paste your API key.");
    println!("  Create one at: https://app.cinchdb.dev/settings/api-keys");
    println!();
    print!("API key: ");
    std::io::stdout().flush()?;

    let mut api_key = String::new();
    std::io::stdin()
        .read_line(&mut api_key)
        .context("failed to read API key")?;
    let api_key = api_key.trim().to_string();
    println!(); // blank line after prompt input

    if api_key.is_empty() {
        anyhow::bail!("no API key provided");
    }

    if !api_key.starts_with("ck_live_") {
        anyhow::bail!("invalid API key format. Keys start with 'ck_live_'");
    }

    // Validate the key by calling /users/me BEFORE saving to disk
    let mut config = ConfigFile::load()?;
    config.auth.api_key = Some(api_key.clone());
    let client = ApiClient::with_config(api_url, &config)?;

    let user: UserInfo = client
        .get("/users/me")
        .await
        .context("API key validation failed")?;

    // Key is valid, now save
    config.save()?;

    output::print_success(
        &format!("Authenticated as {}", user.email),
        Some("cinch db create mydb --type redis"),
    );

    // Auto-set org context if user has exactly one org
    if let Ok(orgs) = client.get::<UserOrgsResponse>("/users/me/orgs").await {
        if orgs.organizations.len() == 1 {
            let org = &orgs.organizations[0];
            config.context.org = Some(org.slug.clone());
            config.save()?;
            println!("  Set org context to \"{}\"", org.slug);
        }
    }

    Ok(())
}

/// Logout: clear credentials and optionally invalidate the server session
async fn logout(api_url: &str, json: bool) -> Result<()> {
    let mut config = ConfigFile::load()?;

    // Best-effort server-side session invalidation. If the API is unreachable,
    // we still clear local credentials. The JWT will expire server-side on its own.
    if config.auth.token.is_some() {
        if let Ok(client) = ApiClient::new(api_url) {
            let _ = client.post_empty("/auth/logout").await;
        }
    }

    config.auth.token = None;
    config.auth.api_key = None;
    config.save()?;

    if json {
        println!("{}", serde_json::json!({ "status": "logged_out" }));
    } else {
        println!("Logged out.");
    }

    Ok(())
}

/// Show current user and context
async fn whoami(api_url: &str, json: bool) -> Result<()> {
    let config = ConfigFile::load()?;

    if config.auth_header_value().is_none() {
        anyhow::bail!("not logged in. Run `cinch auth login` first.");
    }

    let client = ApiClient::new(api_url)?;
    let user: UserInfo = client.get("/users/me").await?;
    let context = crate::config::resolve_context(&config);

    if json {
        let data = serde_json::json!({
            "user": {
                "id": user.id,
                "email": user.email,
                "plan": user.plan,
            },
            "context": {
                "org": context.org,
                "project": context.project,
                "environment": context.environment,
                "scope": context.scope,
            }
        });
        println!("{}", serde_json::to_string_pretty(&data).expect("json serialization failed"));
    } else {
        let plan = user.plan.as_deref().unwrap_or("unknown");
        println!("  {}   {}", colored::Colorize::bold("Email"), user.email);
        println!("  {}      {}", colored::Colorize::bold("ID"), user.id);
        println!("  {}    {}", colored::Colorize::bold("Plan"), plan);
        println!();
        println!("  {}", colored::Colorize::bold("Context"));
        println!(
            "    org:         {}",
            context.org.as_deref().unwrap_or("(not set)")
        );
        println!(
            "    project:     {}",
            context.project.as_deref().unwrap_or("(not set)")
        );
        println!(
            "    environment: {}",
            context.environment.as_deref().unwrap_or("(not set)")
        );
        println!(
            "    scope:       {}",
            context.scope.as_deref().unwrap_or("(not set)")
        );
    }

    Ok(())
}

/// API key management
async fn api_keys(command: ApiKeyCommands, api_url: &str, json: bool) -> Result<()> {
    let client = ApiClient::new(api_url)?;

    match command {
        ApiKeyCommands::Create { name } => {
            let body = serde_json::json!({
                "name": name.unwrap_or_else(|| "cli".to_string()),
            });
            let key: ApiKeyCreated = client.post("/users/me/api-keys", &body).await?;

            if json {
                println!("{}", serde_json::to_string_pretty(&key).expect("json serialization failed"));
            } else {
                println!("  API key created. Save it now; it won't be shown again:");
                println!();
                println!("  {}", key.api_key);
                println!();
                println!(
                    "  {}: cinch auth login --headless",
                    colored::Colorize::cyan("hint")
                );
            }
            Ok(())
        }
        ApiKeyCommands::List => {
            let keys: ApiKeysResponse = client.get("/users/me/api-keys").await?;
            let rows: Vec<Vec<String>> = keys
                .api_keys
                .iter()
                .map(|k| {
                    vec![
                        k.id.clone(),
                        k.name.clone(),
                        format!("ck_live_{}...", &k.key_prefix),
                        output::format_timestamp_ms(k.created_at),
                    ]
                })
                .collect();
            output::print_table_or_json(
                &["ID", "Name", "Prefix", "Created"],
                rows,
                &keys,
                json,
            );
            Ok(())
        }
        ApiKeyCommands::Revoke { key_id } => {
            client.delete(&format!("/users/me/api-keys/{key_id}")).await?;
            if json {
                println!("{}", serde_json::json!({ "status": "revoked", "key_id": key_id }));
            } else {
                println!("API key {key_id} revoked.");
            }
            Ok(())
        }
    }
}

// ============================================================================
// API response types
// ============================================================================

/// Matches GET /users/me response (UserInfo in control plane types.rs)
#[derive(Debug, Deserialize, Serialize)]
pub struct UserInfo {
    pub id: String,
    pub email: String,
    #[serde(default)]
    pub plan: Option<String>,
    #[serde(default)]
    pub allowed: Option<bool>,
    #[serde(default)]
    pub created_at: Option<i64>,
}

/// Matches GET /users/me/orgs -> ListOrgsResponse
#[derive(Debug, Deserialize)]
struct UserOrgsResponse {
    organizations: Vec<OrgInfo>,
}

/// Matches OrgWithRoleResponse
#[derive(Debug, Deserialize)]
struct OrgInfo {
    slug: String,
    #[allow(dead_code)]
    name: String,
}

/// Matches POST /users/me/api-keys -> CreateApiKeyResponse
#[derive(Debug, Deserialize, Serialize)]
struct ApiKeyCreated {
    id: String,
    api_key: String,
    name: String,
    key_prefix: String,
    created_at: i64,
}

/// Matches GET /users/me/api-keys -> ListApiKeysResponse
#[derive(Debug, Deserialize, Serialize)]
struct ApiKeysResponse {
    api_keys: Vec<ApiKeyInfo>,
}

/// Matches ApiKeyListItem
#[derive(Debug, Deserialize, Serialize)]
struct ApiKeyInfo {
    id: String,
    name: String,
    key_prefix: String,
    #[serde(default)]
    last_used_at: Option<i64>,
    created_at: i64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_user_info_deserialize_minimal() {
        let json = r#"{"id": "usr_123", "email": "test@example.com"}"#;
        let user: UserInfo = serde_json::from_str(json).expect("parse");
        assert_eq!(user.id, "usr_123");
        assert_eq!(user.email, "test@example.com");
        assert!(user.plan.is_none());
    }

    #[test]
    fn test_user_info_deserialize_full() {
        let json = r#"{"id": "usr_123", "email": "test@example.com", "plan": "hobby", "allowed": true, "created_at": 1700000000}"#;
        let user: UserInfo = serde_json::from_str(json).expect("parse");
        assert_eq!(user.plan.as_deref(), Some("hobby"));
        assert_eq!(user.allowed, Some(true));
        assert_eq!(user.created_at, Some(1700000000));
    }

    #[test]
    fn test_api_key_validation() {
        assert!("ck_live_abc123def456".starts_with("ck_live_"));
        assert!(!"sk_test_abc".starts_with("ck_live_"));
        assert!(!"".starts_with("ck_live_"));
    }

    #[test]
    fn test_callback_url_parsing() {
        let request = "GET /callback?token=eyJhbGciOiJIUzI1NiJ9.test HTTP/1.1\r\nHost: 127.0.0.1:12345\r\n";
        let token = request
            .lines()
            .next()
            .and_then(|line| {
                let path = line.split_whitespace().nth(1)?;
                let query = path.split('?').nth(1)?;
                query
                    .split('&')
                    .find_map(|param| param.strip_prefix("token="))
            })
            .map(|t| t.to_string());

        assert_eq!(token.as_deref(), Some("eyJhbGciOiJIUzI1NiJ9.test"));
    }

    #[test]
    fn test_callback_url_no_token() {
        let request = "GET /callback?other=value HTTP/1.1\r\n";
        let token = request
            .lines()
            .next()
            .and_then(|line| {
                let path = line.split_whitespace().nth(1)?;
                let query = path.split('?').nth(1)?;
                query
                    .split('&')
                    .find_map(|param| param.strip_prefix("token="))
            })
            .map(|t| t.to_string());

        assert!(token.is_none());
    }

    #[test]
    fn test_callback_url_multiple_params() {
        let request = "GET /callback?state=abc&token=jwt123&other=val HTTP/1.1\r\n";
        let token = request
            .lines()
            .next()
            .and_then(|line| {
                let path = line.split_whitespace().nth(1)?;
                let query = path.split('?').nth(1)?;
                query
                    .split('&')
                    .find_map(|param| param.strip_prefix("token="))
            })
            .map(|t| t.to_string());

        assert_eq!(token.as_deref(), Some("jwt123"));
    }

    #[test]
    fn test_orgs_response_deserialize() {
        let json = r#"{"organizations": [{"slug": "acme", "name": "Acme Corp"}]}"#;
        let resp: UserOrgsResponse = serde_json::from_str(json).expect("parse");
        assert_eq!(resp.organizations.len(), 1);
        assert_eq!(resp.organizations[0].slug, "acme");
    }

    #[test]
    fn test_api_keys_response_deserialize() {
        let json = r#"{"api_keys": [{"id": "key_1", "name": "cli", "key_prefix": "ck_live_ab", "created_at": 1700000000}]}"#;
        let resp: ApiKeysResponse = serde_json::from_str(json).expect("parse");
        assert_eq!(resp.api_keys.len(), 1);
        assert_eq!(resp.api_keys[0].key_prefix, "ck_live_ab");
    }

    #[test]
    fn test_resolve_dashboard_url_production() {
        std::env::remove_var("CINCH_DASHBOARD_URL");
        assert_eq!(
            resolve_dashboard_url("https://api.cinchdb.dev"),
            "https://app.cinchdb.dev"
        );
    }

    #[test]
    fn test_resolve_dashboard_url_staging() {
        std::env::remove_var("CINCH_DASHBOARD_URL");
        assert_eq!(
            resolve_dashboard_url("https://api-staging.cinchdb.dev"),
            "https://app-staging.cinchdb.dev"
        );
    }

    #[test]
    fn test_resolve_dashboard_url_localhost() {
        std::env::remove_var("CINCH_DASHBOARD_URL");
        assert_eq!(
            resolve_dashboard_url("http://localhost:8080"),
            "http://localhost:5200"
        );
        assert_eq!(
            resolve_dashboard_url("http://127.0.0.1:8080"),
            "http://127.0.0.1:5200"
        );
    }

    #[test]
    fn test_resolve_dashboard_url_env_override() {
        std::env::set_var("CINCH_DASHBOARD_URL", "https://custom.dashboard.dev");
        assert_eq!(
            resolve_dashboard_url("https://api.cinchdb.dev"),
            "https://custom.dashboard.dev"
        );
        std::env::remove_var("CINCH_DASHBOARD_URL");
    }
}