wavekat-cli 0.0.4

Command-line client for the WaveKat platform (wk)
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
// `wk login` — loopback OAuth flow.
//
// The CLI:
//   1. Binds a TCP listener on 127.0.0.1:<random ephemeral port>.
//   2. Generates a one-shot CSRF state.
//   3. Opens the platform's `/cli-login` page in the user's default
//      browser, with the loopback URL and state as query params.
//   4. Blocks on `accept()` until the platform redirects the browser
//      back to the loopback URL with `?token=…&state=…` (success) or
//      `?error=…&state=…` (cancel/error).
//   5. Verifies the token by calling `/api/me`, persists it, and
//      returns control.
//
// The loopback HTTP server is intentionally hand-rolled (std::net):
// one request, one response, no concurrency, no need to drag in a
// framework. The handler reads at most a small fixed amount per
// connection so a stray local probe can't tie us up.
//
// `--no-browser` falls back to printing the URL for the user to open
// manually — useful on a remote host where no browser is available.
// `--token` skips the dance entirely (e.g. for CI), accepting a
// pre-minted `wkcli_…` token.

use anyhow::{anyhow, bail, Context, Result};
use clap::Args as ClapArgs;
use rand::RngCore;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream};
use std::time::Duration;

use crate::client::Client;
use crate::config::{self, AuthConfig};
use crate::style;

const DEFAULT_BASE_URL: &str = "https://platform.wavekat.com";

#[derive(ClapArgs)]
pub struct Args {
    /// Base URL of the WaveKat platform (e.g. https://platform.wavekat.com).
    /// If omitted, the previously stored value is reused, then the public
    /// platform URL.
    #[arg(long, env = "WK_BASE_URL")]
    base_url: Option<String>,

    /// Skip opening the browser; print the URL instead. Useful on a remote
    /// host. The CLI still listens on a loopback port — open the URL on
    /// any browser that can reach this machine on that port (typically via
    /// SSH port-forward).
    #[arg(long)]
    no_browser: bool,

    /// Pre-minted `wkcli_…` bearer token. Skips the browser handshake
    /// entirely and just verifies + saves the token. Intended for CI.
    /// Read from `WK_TOKEN` if set.
    #[arg(long, env = "WK_TOKEN")]
    token: Option<String>,
}

pub async fn run(args: Args) -> Result<()> {
    let existing = config::load().ok();

    let base_url = args
        .base_url
        .or_else(|| existing.as_ref().map(|c| c.base_url.clone()))
        .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
        .trim_end_matches('/')
        .to_string();

    let token = match args.token {
        Some(t) => t.trim().to_string(),
        None => browser_handshake(&base_url, args.no_browser)?,
    };
    if token.is_empty() {
        bail!("got an empty token from the platform");
    }

    let cfg = AuthConfig {
        base_url,
        token: Some(token),
        session_cookie: None,
    };

    // Verify against /api/me before persisting — keeps a typo or a
    // half-broken handshake from poisoning the saved config.
    let client = Client::new(&cfg)?;
    let me: serde_json::Value = client
        .get_json("/api/me")
        .await
        .context("verifying token against /api/me")?;
    let login = me.get("login").and_then(|v| v.as_str()).unwrap_or("?");
    let role = me.get("role").and_then(|v| v.as_str()).unwrap_or("?");

    config::save(&cfg)?;
    let path = config::auth_path()?;
    println!(
        "{} Signed in as {} ({} {}).",
        style::green("✓"),
        style::bold(login),
        style::dim("role:"),
        style::role(role),
    );
    println!(
        "{} {}",
        style::dim("Credentials saved to"),
        style::dim(&path.display().to_string()),
    );
    Ok(())
}

fn browser_handshake(base_url: &str, no_browser: bool) -> Result<String> {
    // Bind to an ephemeral port on loopback only — never on 0.0.0.0,
    // since anything bound to a non-loopback interface could be reached
    // by another host on the network for the brief window we listen.
    let listener = TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0))
        .context("binding loopback listener for the OAuth handshake")?;
    let port = listener.local_addr()?.port();

    let state = random_state();
    let name = client_name();
    let callback = format!("http://127.0.0.1:{port}/callback");

    let auth_url = format!(
        "{base_url}/cli-login?callback={cb}&state={state}&name={name}",
        cb = url::form_urlencoded::byte_serialize(callback.as_bytes()).collect::<String>(),
        state = url::form_urlencoded::byte_serialize(state.as_bytes()).collect::<String>(),
        name = url::form_urlencoded::byte_serialize(name.as_bytes()).collect::<String>(),
    );

    if no_browser {
        println!("Open this URL in any browser to finish signing in:\n  {auth_url}\n");
    } else {
        println!("Opening {base_url} in your browser to sign in…");
        if let Err(e) = webbrowser::open(&auth_url) {
            eprintln!("(couldn't open the browser automatically: {e})");
            println!("Open this URL manually:\n  {auth_url}\n");
        }
    }
    println!("Waiting for the browser to redirect back (Ctrl-C to cancel)…");

    // 5 minutes is generous — if a user takes longer than that to log in
    // they probably got distracted. Re-running `wk login` is cheap.
    listener
        .set_nonblocking(false)
        .context("listener: set_blocking")?;
    let deadline = std::time::Instant::now() + Duration::from_secs(5 * 60);

    loop {
        if std::time::Instant::now() > deadline {
            bail!("timed out waiting for the browser to complete the login");
        }
        let (stream, _) = listener
            .accept()
            .context("accepting browser callback connection")?;
        match handle_callback(stream, &state) {
            Ok(Some(token)) => return Ok(token),
            Ok(None) => continue, // probe / preflight; keep listening
            Err(e) => {
                // Surface but don't abort — a stray request shouldn't break
                // the real one. (e.g. devtools sending a HEAD probe.)
                eprintln!("(ignored bad callback request: {e})");
                continue;
            }
        }
    }
}

fn handle_callback(mut stream: TcpStream, expected_state: &str) -> Result<Option<String>> {
    stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
    stream.set_write_timeout(Some(Duration::from_secs(5))).ok();

    // Read just the request line + headers. Cap at 8 KiB — the URL we care
    // about is well under that and we never need the body.
    let mut reader = BufReader::new(stream.try_clone()?);
    let mut request_line = String::new();
    reader
        .read_line(&mut request_line)
        .context("reading HTTP request line")?;
    // Drain headers (and discard) so the browser sees the connection close
    // cleanly. Bounded to keep a malicious local probe from streaming forever.
    let mut header_bytes = 0usize;
    let mut line = String::new();
    loop {
        line.clear();
        let n = reader.read_line(&mut line)?;
        if n == 0 || line == "\r\n" || line == "\n" {
            break;
        }
        header_bytes += n;
        if header_bytes > 8192 {
            bail!("request headers too large");
        }
    }

    // Parse "GET /callback?... HTTP/1.1"
    let mut parts = request_line.split_whitespace();
    let method = parts.next().unwrap_or("");
    let target = parts.next().unwrap_or("");
    if method != "GET" {
        respond(&mut stream, 405, "method not allowed", "method not allowed")?;
        return Ok(None);
    }
    if !target.starts_with("/callback") {
        // Browsers fetch /favicon.ico; OS sometimes probes /. Reply 404 and
        // keep listening — only /callback matters.
        respond(&mut stream, 404, "not found", "not found")?;
        return Ok(None);
    }

    let query = target.split_once('?').map(|(_, q)| q).unwrap_or("");
    let mut token: Option<String> = None;
    let mut state: Option<String> = None;
    let mut error: Option<String> = None;
    for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
        match k.as_ref() {
            "token" => token = Some(v.into_owned()),
            "state" => state = Some(v.into_owned()),
            "error" => error = Some(v.into_owned()),
            _ => {}
        }
    }

    // Constant-time enough: states are short, equal length on success path.
    if state.as_deref() != Some(expected_state) {
        respond(
            &mut stream,
            400,
            "bad state",
            "<h1>State mismatch</h1><p>Re-run <code>wk login</code> to start over.</p>",
        )?;
        bail!("state mismatch — refusing token");
    }

    if let Some(err) = error {
        respond(
            &mut stream,
            200,
            "OK",
            &format!(
                "<h1>Login cancelled</h1><p>You can close this tab and re-run <code>wk login</code>.</p><p style='color:#888'>reason: {}</p>",
                html_escape(&err),
            ),
        )?;
        bail!("login cancelled in browser ({err})");
    }

    let Some(tok) = token else {
        respond(&mut stream, 400, "missing token", "missing token")?;
        bail!("callback missing token");
    };

    respond(
        &mut stream,
        200,
        "OK",
        "<!doctype html><html><head><meta charset=utf-8><title>WaveKat CLI signed in</title><style>body{font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#1a1a1a}code{background:#f3f4f6;padding:.1em .3em;border-radius:.25em}</style></head><body><h1>You're signed in.</h1><p>You can close this tab and return to your terminal.</p></body></html>",
    )?;
    Ok(Some(tok))
}

fn respond(stream: &mut TcpStream, status: u16, reason: &str, body: &str) -> Result<()> {
    let body_bytes = body.as_bytes();
    let resp = format!(
        "HTTP/1.1 {status} {reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {len}\r\nConnection: close\r\n\r\n",
        len = body_bytes.len(),
    );
    stream.write_all(resp.as_bytes())?;
    stream.write_all(body_bytes)?;
    // Drain any unread bytes so the kernel doesn't RST the connection
    // before the browser reads our response.
    let _ = stream.flush();
    let mut sink = [0u8; 64];
    let _ = stream.set_read_timeout(Some(Duration::from_millis(50)));
    let _ = stream.read(&mut sink);
    Ok(())
}

fn random_state() -> String {
    let mut bytes = [0u8; 24];
    rand::thread_rng().fill_bytes(&mut bytes);
    // URL-safe base64 (manual, to avoid pulling in another crate).
    base64url(&bytes)
}

fn base64url(bytes: &[u8]) -> String {
    const ALPHA: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity((bytes.len() * 4).div_ceil(3));
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
        out.push(ALPHA[((n >> 18) & 0x3f) as usize] as char);
        out.push(ALPHA[((n >> 12) & 0x3f) as usize] as char);
        out.push(ALPHA[((n >> 6) & 0x3f) as usize] as char);
        out.push(ALPHA[(n & 0x3f) as usize] as char);
        i += 3;
    }
    let rem = bytes.len() - i;
    if rem == 1 {
        let n = (bytes[i] as u32) << 16;
        out.push(ALPHA[((n >> 18) & 0x3f) as usize] as char);
        out.push(ALPHA[((n >> 12) & 0x3f) as usize] as char);
    } else if rem == 2 {
        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
        out.push(ALPHA[((n >> 18) & 0x3f) as usize] as char);
        out.push(ALPHA[((n >> 12) & 0x3f) as usize] as char);
        out.push(ALPHA[((n >> 6) & 0x3f) as usize] as char);
    }
    out
}

fn client_name() -> String {
    let host = std::env::var("HOSTNAME")
        .ok()
        .or_else(|| hostname().ok())
        .unwrap_or_else(|| "unknown-host".to_string());
    format!("wavekat-cli on {host}")
}

#[cfg(unix)]
fn hostname() -> Result<String> {
    let out = std::process::Command::new("hostname").output()?;
    if !out.status.success() {
        return Err(anyhow!("hostname exited non-zero"));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

#[cfg(not(unix))]
fn hostname() -> Result<String> {
    std::env::var("COMPUTERNAME").map_err(|e| anyhow!(e))
}

fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

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

    // RFC 4648 test vectors, adapted to URL-safe alphabet without padding.
    #[test]
    fn base64url_rfc_vectors() {
        assert_eq!(base64url(b""), "");
        assert_eq!(base64url(b"f"), "Zg");
        assert_eq!(base64url(b"fo"), "Zm8");
        assert_eq!(base64url(b"foo"), "Zm9v");
        assert_eq!(base64url(b"foob"), "Zm9vYg");
        assert_eq!(base64url(b"fooba"), "Zm9vYmE");
        assert_eq!(base64url(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn base64url_uses_url_safe_alphabet() {
        // Bytes that would yield `+` and `/` under standard base64.
        // 0xfb,0xff,0xff -> 6-bit indices 62, 63, 63, 63 -> "-___".
        assert_eq!(base64url(&[0xfb, 0xff, 0xff]), "-___");
        // Confirm none of the disallowed characters ever appear.
        let big: Vec<u8> = (0u8..=255).collect();
        let out = base64url(&big);
        assert!(!out.contains('+'));
        assert!(!out.contains('/'));
        assert!(!out.contains('='));
    }

    #[test]
    fn random_state_shape() {
        let s = random_state();
        // 24 bytes -> 32 base64url chars (no padding).
        assert_eq!(s.len(), 32);
        let alpha: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
        for b in s.as_bytes() {
            assert!(alpha.contains(b), "unexpected byte {b:#x} in state");
        }
    }

    #[test]
    fn random_state_is_not_constant() {
        // Astronomically unlikely to collide; protects against an accidental
        // hard-coded or zeroed RNG.
        assert_ne!(random_state(), random_state());
    }

    #[test]
    fn html_escape_handles_metacharacters() {
        assert_eq!(
            html_escape("<a href=\"x\">it's & ok</a>"),
            "&lt;a href=&quot;x&quot;&gt;it&#39;s &amp; ok&lt;/a&gt;",
        );
        assert_eq!(html_escape("plain text"), "plain text");
        assert_eq!(html_escape(""), "");
    }
}