siphon-tui 0.1.1

TUI dashboard and setup wizard for Siphon tunnel client
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
//! Styled CLI setup wizard for configuring Siphon connection settings

use std::borrow::Cow;
use std::io;

use crossterm::cursor::MoveUp;
use crossterm::execute;
use crossterm::style::{Attribute, Color, Print, ResetColor, SetAttribute, SetForegroundColor};
use crossterm::terminal::{Clear, ClearType};
use rustyline::completion::{Completer, FilenameCompleter, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::history::DefaultHistory;
use rustyline::validate::Validator;
use rustyline::{Config, Editor, Helper};

use crate::config::SiphonConfig;

/// Path completer helper for rustyline
struct PathHelper {
    completer: FilenameCompleter,
}

impl PathHelper {
    fn new() -> Self {
        Self {
            completer: FilenameCompleter::new(),
        }
    }
}

impl Completer for PathHelper {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        self.completer.complete(line, pos, ctx)
    }
}

impl Hinter for PathHelper {
    type Hint = String;
}

impl Highlighter for PathHelper {
    fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
        &'s self,
        prompt: &'p str,
        _default: bool,
    ) -> Cow<'b, str> {
        Cow::Borrowed(prompt)
    }
}

impl Validator for PathHelper {}

impl Helper for PathHelper {}

/// Setup wizard for interactive configuration
pub struct SetupWizard {
    config: SiphonConfig,
}

impl SetupWizard {
    /// Create a new setup wizard
    pub fn new() -> Self {
        Self {
            config: SiphonConfig::default(),
        }
    }

    /// Run the setup wizard
    pub fn run(&mut self) -> anyhow::Result<Option<SiphonConfig>> {
        let mut stdout = io::stdout();

        // Create rustyline editors
        let config = Config::builder().auto_add_history(false).build();
        let mut text_editor: Editor<(), DefaultHistory> = Editor::with_config(config.clone())?;
        let mut path_editor: Editor<PathHelper, DefaultHistory> = Editor::with_config(config)?;
        path_editor.set_helper(Some(PathHelper::new()));

        // Header
        println!();
        self.print_header(&mut stdout)?;
        println!();

        self.print_dim(
            &mut stdout,
            "This will configure your connection to the tunnel server.",
        )?;
        self.print_dim(
            &mut stdout,
            "Runtime options (--local, --subdomain) are provided when starting.",
        )?;
        println!();
        println!();

        // Step 1: Server address
        self.print_step(&mut stdout, 1, 4, "Server Connection")?;
        let server_addr = self.prompt_text(
            &mut stdout,
            &mut text_editor,
            "Server address",
            "tunnel.example.com:4443",
        )?;
        let server_addr = match server_addr {
            Some(addr) => addr,
            None => return Ok(None),
        };

        if server_addr.is_empty() {
            self.print_error(&mut stdout, "Server address is required.")?;
            return Ok(None);
        }

        // Add default port if not specified
        self.config.server_addr = if server_addr.contains(':') {
            server_addr
        } else {
            format!("{}:4443", server_addr)
        };

        self.clear_prompt_lines(&mut stdout, 2)?;
        self.print_success(&mut stdout, &format!("Server: {}", self.config.server_addr))?;
        println!();

        // Step 2: Client certificate
        self.print_step(&mut stdout, 2, 4, "Client Certificate")?;
        let cert_path = self.prompt_path(
            &mut stdout,
            &mut path_editor,
            "Certificate path",
            "~/certs/client.crt",
        )?;
        let cert_path = match cert_path {
            Some(path) => path,
            None => return Ok(None),
        };

        if cert_path.is_empty() {
            self.print_error(&mut stdout, "Certificate is required.")?;
            return Ok(None);
        }

        let cert_pem = match self.load_and_validate_cert(&cert_path, "certificate") {
            Ok(pem) => pem,
            Err(e) => {
                self.print_error(&mut stdout, &e.to_string())?;
                return Ok(None);
            }
        };

        self.clear_prompt_lines(&mut stdout, 2)?;
        self.print_success(&mut stdout, &format!("Certificate: {}", cert_path))?;
        println!();

        // Step 3: Private key
        self.print_step(&mut stdout, 3, 4, "Private Key")?;
        let key_path = self.prompt_path(
            &mut stdout,
            &mut path_editor,
            "Private key path",
            "~/certs/client.key",
        )?;
        let key_path = match key_path {
            Some(path) => path,
            None => return Ok(None),
        };

        if key_path.is_empty() {
            self.print_error(&mut stdout, "Private key is required.")?;
            return Ok(None);
        }

        let key_pem = match self.load_and_validate_key(&key_path) {
            Ok(pem) => pem,
            Err(e) => {
                self.print_error(&mut stdout, &e.to_string())?;
                return Ok(None);
            }
        };

        self.clear_prompt_lines(&mut stdout, 2)?;
        self.print_success(&mut stdout, &format!("Private key: {}", key_path))?;
        println!();

        // Step 4: CA certificate
        self.print_step(&mut stdout, 4, 4, "CA Certificate")?;
        let ca_path = self.prompt_path(
            &mut stdout,
            &mut path_editor,
            "CA certificate path",
            "~/certs/ca.crt",
        )?;
        let ca_path = match ca_path {
            Some(path) => path,
            None => return Ok(None),
        };

        if ca_path.is_empty() {
            self.print_error(&mut stdout, "CA certificate is required.")?;
            return Ok(None);
        }

        let ca_pem = match self.load_and_validate_cert(&ca_path, "CA certificate") {
            Ok(pem) => pem,
            Err(e) => {
                self.print_error(&mut stdout, &e.to_string())?;
                return Ok(None);
            }
        };

        self.clear_prompt_lines(&mut stdout, 2)?;
        self.print_success(&mut stdout, &format!("CA certificate: {}", ca_path))?;
        println!();

        // Try keychain first, fall back to base64 in config
        self.print_action(&mut stdout, "Storing credentials...")?;

        let keychain_works = self.try_keychain_storage(&cert_pem, &key_pem, &ca_pem);

        self.clear_prompt_lines(&mut stdout, 1)?;

        if keychain_works {
            // Use keychain references
            self.config.cert = "keychain://siphon/cert".to_string();
            self.config.key = "keychain://siphon/key".to_string();
            self.config.ca_cert = "keychain://siphon/ca".to_string();
            self.print_success(&mut stdout, "Credentials stored in OS keychain")?;
        } else {
            // Fall back to base64 in config
            use base64::Engine;
            let engine = base64::engine::general_purpose::STANDARD;
            self.config.cert = format!("base64://{}", engine.encode(&cert_pem));
            self.config.key = format!("base64://{}", engine.encode(&key_pem));
            self.config.ca_cert = format!("base64://{}", engine.encode(&ca_pem));
            self.print_success(&mut stdout, "Credentials will be stored in config file")?;
        }

        // Save config
        let config_path = SiphonConfig::default_path();
        self.print_action(
            &mut stdout,
            &format!("Saving configuration to {:?}...", config_path),
        )?;
        if let Err(e) = self.config.save_default() {
            self.print_error(&mut stdout, &format!("Failed to save config: {}", e))?;
            return Ok(None);
        }
        self.clear_prompt_lines(&mut stdout, 1)?;

        // Verify file was created
        if !config_path.exists() {
            self.print_error(&mut stdout, "Config file was not created!")?;
            return Ok(None);
        }
        self.print_success(
            &mut stdout,
            &format!("Config saved to {}", config_path.display()),
        )?;

        println!();
        self.print_complete(&mut stdout)?;

        Ok(Some(self.config.clone()))
    }

    fn clear_prompt_lines(&self, stdout: &mut io::Stdout, lines: u16) -> anyhow::Result<()> {
        for _ in 0..lines {
            execute!(stdout, MoveUp(1), Clear(ClearType::CurrentLine))?;
        }
        Ok(())
    }

    fn print_header(&self, stdout: &mut io::Stdout) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::Cyan),
            SetAttribute(Attribute::Bold),
            Print("◆ Siphon Setup"),
            ResetColor,
            SetAttribute(Attribute::Reset),
        )?;
        println!();
        Ok(())
    }

    fn print_step(
        &self,
        stdout: &mut io::Stdout,
        current: u8,
        total: u8,
        title: &str,
    ) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::Blue),
            Print(format!("[{}/{}] ", current, total)),
            SetForegroundColor(Color::White),
            SetAttribute(Attribute::Bold),
            Print(title),
            ResetColor,
            SetAttribute(Attribute::Reset),
        )?;
        println!();
        Ok(())
    }

    fn print_success(&self, stdout: &mut io::Stdout, message: &str) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::Green),
            Print(""),
            ResetColor,
            Print(message),
        )?;
        println!();
        Ok(())
    }

    fn print_error(&self, stdout: &mut io::Stdout, message: &str) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::Red),
            Print(""),
            ResetColor,
            Print(message),
        )?;
        println!();
        Ok(())
    }

    fn print_action(&self, stdout: &mut io::Stdout, message: &str) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::Cyan),
            Print(""),
            ResetColor,
            Print(message),
        )?;
        println!();
        Ok(())
    }

    fn print_dim(&self, stdout: &mut io::Stdout, message: &str) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::DarkGrey),
            Print(format!("  {}", message)),
            ResetColor,
        )?;
        println!();
        Ok(())
    }

    fn print_complete(&self, stdout: &mut io::Stdout) -> anyhow::Result<()> {
        execute!(
            stdout,
            SetForegroundColor(Color::Green),
            SetAttribute(Attribute::Bold),
            Print("◆ Setup complete!"),
            ResetColor,
            SetAttribute(Attribute::Reset),
        )?;
        println!();
        println!();
        execute!(
            stdout,
            Print("  Start a tunnel with: "),
            SetForegroundColor(Color::Cyan),
            Print("siphon --local 127.0.0.1:3000"),
            ResetColor,
        )?;
        println!();
        println!();
        Ok(())
    }

    fn prompt_text(
        &self,
        stdout: &mut io::Stdout,
        editor: &mut Editor<(), DefaultHistory>,
        label: &str,
        placeholder: &str,
    ) -> anyhow::Result<Option<String>> {
        execute!(
            stdout,
            SetForegroundColor(Color::White),
            Print(format!("  {} ", label)),
            SetForegroundColor(Color::DarkGrey),
            Print(format!("({})", placeholder)),
            ResetColor,
        )?;
        println!();

        // Build colored prompt
        let prompt = "\x1b[36m  › \x1b[0m";

        match editor.readline(prompt) {
            Ok(line) => Ok(Some(line.trim().to_string())),
            Err(ReadlineError::Interrupted | ReadlineError::Eof) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    fn prompt_path(
        &self,
        stdout: &mut io::Stdout,
        editor: &mut Editor<PathHelper, DefaultHistory>,
        label: &str,
        placeholder: &str,
    ) -> anyhow::Result<Option<String>> {
        execute!(
            stdout,
            SetForegroundColor(Color::White),
            Print(format!("  {} ", label)),
            SetForegroundColor(Color::DarkGrey),
            Print(format!("({})", placeholder)),
            ResetColor,
        )?;
        println!();

        // Build colored prompt
        let prompt = "\x1b[36m  › \x1b[0m";

        match editor.readline(prompt) {
            Ok(line) => Ok(Some(line.trim().to_string())),
            Err(ReadlineError::Interrupted | ReadlineError::Eof) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    /// Try to store credentials in keychain and verify they can be read back
    fn try_keychain_storage(&self, cert_pem: &str, key_pem: &str, ca_pem: &str) -> bool {
        // Try to store
        if siphon_secrets::keychain::store("siphon", "cert", cert_pem).is_err() {
            return false;
        }
        if siphon_secrets::keychain::store("siphon", "key", key_pem).is_err() {
            return false;
        }
        if siphon_secrets::keychain::store("siphon", "ca", ca_pem).is_err() {
            return false;
        }

        // Verify we can read them back
        siphon_secrets::keychain::resolve("siphon", "cert").is_ok()
    }

    fn load_and_validate_cert(&self, path: &str, name: &str) -> anyhow::Result<String> {
        let expanded = shellexpand::tilde(path);
        let content = std::fs::read_to_string(expanded.as_ref())
            .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", path, e))?;

        if !content.contains("-----BEGIN CERTIFICATE-----") {
            anyhow::bail!("Invalid {}: must be PEM format", name);
        }

        Ok(content)
    }

    fn load_and_validate_key(&self, path: &str) -> anyhow::Result<String> {
        let expanded = shellexpand::tilde(path);
        let content = std::fs::read_to_string(expanded.as_ref())
            .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", path, e))?;

        if !content.contains("-----BEGIN") || !content.contains("PRIVATE KEY-----") {
            anyhow::bail!("Invalid private key: must be PEM format");
        }

        Ok(content)
    }
}

impl Default for SetupWizard {
    fn default() -> Self {
        Self::new()
    }
}