ssh-portkey 0.1.4

Secure SSH credential manager with a fast ratatui-based TUI, fuzzy search, and encrypted vault
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
use anyhow::Result;
use clap::{Parser, Subcommand};
use inquire::{Confirm, Password, Select, Text};
use std::cmp::Reverse;

use crate::models::Server;
use crate::ssh;
use crate::ssh_config::{render_managed_block, upsert_managed_block};
use crate::tui;
use crate::vault::Vault;
use fuzzy_matcher::FuzzyMatcher;
use uuid::Uuid;

pub fn password_option_from_choice(use_password: bool, password: &str) -> Result<Option<&str>> {
    if use_password && password.is_empty() {
        return Err(anyhow::anyhow!(
            "Master password cannot be empty when password protection is enabled"
        ));
    }

    Ok(if use_password { Some(password) } else { None })
}

#[derive(Parser)]
#[command(name = "portkey")]
#[command(about = "Secure SSH credential manager")]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Initialize a new vault
    Init,

    /// Add a new server
    Add,

    /// List all servers
    List,

    /// Connect to a server
    Connect {
        /// Server name or ID
        name: Option<String>,
    },

    /// Remove a server
    Remove {
        /// Server name or ID
        name: String,
    },

    /// Interactive server selection and connection
    Quick,

    /// Search servers
    Search { query: String },

    /// Export SSH config entries for servers
    SshConfig {
        /// Actually write to ~/.ssh/config instead of printing
        #[arg(long)]
        write: bool,
    },

    /// Full-screen TUI application
    Ui,
}

pub struct CliHandler {
    vault: Vault,
}

impl CliHandler {
    pub fn new() -> Result<Self> {
        let vault = Vault::new()?;
        Ok(Self { vault })
    }

    pub async fn run(&mut self) -> Result<()> {
        let cli = Cli::parse();

        match cli.command {
            Some(Commands::Init) => self.handle_init().await?,
            Some(Commands::Add) => self.handle_add().await?,
            Some(Commands::List) => self.handle_list().await?,
            Some(Commands::Connect { name }) => self.handle_connect(name).await?,
            Some(Commands::Remove { name }) => self.handle_remove(name).await?,
            Some(Commands::Quick) => self.handle_quick().await?,
            Some(Commands::Search { query }) => self.handle_search(query).await?,
            Some(Commands::SshConfig { write }) => self.handle_ssh_config(write).await?,
            Some(Commands::Ui) => self.handle_interactive().await?,
            None => self.handle_interactive().await?,
        }

        Ok(())
    }

    async fn handle_init(&mut self) -> Result<()> {
        if self.vault.exists() {
            let confirmed = Confirm::new("Vault already exists. Do you want to overwrite it?")
                .with_default(false)
                .prompt()?;

            if !confirmed {
                println!("Operation cancelled.");
                return Ok(());
            }

            let backup_path = self
                .vault
                .vault_path()
                .with_file_name(format!("vault.dat.{}.bak", Uuid::new_v4()));
            std::fs::rename(self.vault.vault_path(), &backup_path)?;
            println!("Existing vault backed up to {}", backup_path.display());
        }

        let use_password =
            Confirm::new("Would you like to protect your vault with a master password?")
                .with_default(true)
                .prompt()?;

        let password = if use_password {
            Password::new("Enter master password:")
                .with_display_toggle_enabled()
                .prompt()?
        } else {
            println!("Creating vault without password protection...");
            String::new()
        };

        let password_opt = password_option_from_choice(use_password, password.as_str())?;
        self.vault.create(password_opt)?;

        if use_password {
            println!("🔒 Vault created with password protection!");
        } else {
            println!("✅ Vault created without password protection!");
        }

        Ok(())
    }

    async fn handle_add(&mut self) -> Result<()> {
        self.ensure_unlocked().await?;

        let name = Text::new("Server name:").prompt()?;
        let host = Text::new("Host/IP:").prompt()?;
        let port_input = Text::new("Port:").with_default("22").prompt()?;
        let port = port_input
            .parse::<u16>()
            .map_err(|_| anyhow::anyhow!("Invalid port '{}'", port_input))?;
        let username = Text::new("Username:").prompt()?;
        let password = Password::new("Password:")
            .with_display_toggle_enabled()
            .prompt()?;
        let identity_file = Text::new("Identity file (optional, e.g. ~/.ssh/id_ed25519):")
            .prompt()
            .ok()
            .and_then(|value| {
                let trimmed = value.trim().to_string();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed)
                }
            });
        let forward_agent = Confirm::new("Forward SSH agent for this session?")
            .with_default(false)
            .prompt()
            .unwrap_or(false);
        let description = Text::new("Description (optional):").prompt().ok();

        let mut server = Server::new(name, host, port, username, password, description);
        server.identity_file = identity_file;
        server.forward_agent = forward_agent;

        self.vault.add_server(server)?;
        println!("Server added successfully!");

        Ok(())
    }

    async fn handle_list(&mut self) -> Result<()> {
        self.ensure_unlocked().await?;

        let servers = self.vault.list_servers()?;

        if servers.is_empty() {
            println!("No servers configured.");
            return Ok(());
        }

        println!("\nConfigured servers:");
        println!("{:-<60}", "");

        for server in servers {
            println!("ID: {}", server.id);
            println!("Name: {}", server.name);
            println!("Host: {}:{}", server.host, server.port);
            println!("User: {}", server.username);
            if let Some(identity_file) = &server.identity_file {
                println!("Identity file: {identity_file}");
            }
            if server.forward_agent {
                println!("Forward agent: yes");
            }
            if let Some(desc) = &server.description {
                println!("Description: {desc}");
            }
            println!("{:-<60}", "");
        }

        Ok(())
    }

    async fn handle_connect(&mut self, name: Option<String>) -> Result<()> {
        self.ensure_unlocked().await?;

        let server = match name {
            Some(name) => self.find_server_by_name_or_id(&name)?,
            None => {
                let servers = self.vault.list_servers()?;
                if servers.is_empty() {
                    println!("No servers available.");
                    return Ok(());
                }

                let options: Vec<String> = servers
                    .iter()
                    .map(|s| format!("{} ({})", s.name, s.host))
                    .collect();

                let selection = Select::new("Select server:", options).prompt()?;

                let index = servers
                    .iter()
                    .position(|s| format!("{} ({})", s.name, s.host) == selection)
                    .unwrap();

                &servers[index]
            }
        };

        self.connect_to_server(server).await
    }

    async fn handle_remove(&mut self, name: String) -> Result<()> {
        self.ensure_unlocked().await?;

        let server_id = {
            let server = self.find_server_by_name_or_id(&name)?;
            server.id
        };

        let server = self
            .vault
            .find_server(&server_id)?
            .ok_or_else(|| anyhow::anyhow!("Server not found"))?;

        let confirmed = Confirm::new(&format!(
            "Remove server '{}' ({})?",
            server.name, server.host
        ))
        .with_default(false)
        .prompt()?;

        if confirmed {
            self.vault.remove_server(&server_id)?;
            println!("Server removed successfully!");
        } else {
            println!("Operation cancelled.");
        }

        Ok(())
    }

    async fn handle_quick(&mut self) -> Result<()> {
        // Quick now just launches the full TUI
        self.handle_interactive().await
    }

    async fn handle_search(&mut self, query: String) -> Result<()> {
        self.ensure_unlocked().await?;

        let servers = self.vault.list_servers()?;
        let matcher = fuzzy_matcher::skim::SkimMatcherV2::default();
        let mut matches: Vec<(&Server, i64)> = servers
            .iter()
            .filter_map(|s| {
                let hay = format!(
                    "{} {} {} {} {}",
                    s.name,
                    s.host,
                    s.username,
                    s.port,
                    s.description.as_deref().unwrap_or("")
                );
                matcher.fuzzy_match(&hay, &query).map(|score| (s, score))
            })
            .collect();
        matches.sort_by_key(|match_result| Reverse(match_result.1));

        if matches.is_empty() {
            println!("No servers match your search.");
            return Ok(());
        }

        println!("Search results:");
        println!("{:-<60}", "");

        for (server, _) in matches {
            println!("Name: {}", server.name);
            println!("Host: {}:{}", server.host, server.port);
            println!("User: {}", server.username);
            if let Some(identity_file) = &server.identity_file {
                println!("Identity file: {identity_file}");
            }
            if server.forward_agent {
                println!("Forward agent: yes");
            }
            if let Some(desc) = &server.description {
                println!("Description: {desc}");
            }
            println!("{:-<60}", "");
        }

        Ok(())
    }

    async fn handle_ssh_config(&mut self, write: bool) -> Result<()> {
        self.ensure_unlocked().await?;
        let servers = self.vault.list_servers()?;

        let managed_block = render_managed_block(servers)?;

        if write {
            let mut path =
                dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Home directory not found"))?;
            path.push(".ssh");
            std::fs::create_dir_all(&path)?;
            path.push("config");

            use std::io::Write;
            let existing = std::fs::read_to_string(&path).unwrap_or_default();
            let updated = upsert_managed_block(&existing, &managed_block);
            let mut file = std::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&path)?;
            write!(file, "{updated}")?;
            println!("Written SSH config entries to {}", path.display());
        } else {
            println!("# Preview: add these to ~/.ssh/config\n{managed_block}");
        }

        println!("Note: SSH config does not store passwords. Consider setting up SSH keys.");
        Ok(())
    }

    async fn handle_interactive(&mut self) -> Result<()> {
        if !self.vault.exists() {
            println!("No vault found. Run 'portkey init' to create one.");
            return Ok(());
        }

        // Unlock before entering raw mode
        self.ensure_unlocked().await?;
        tui::run_full_ui(&mut self.vault).map_err(|e| anyhow::anyhow!(e))
    }

    async fn ensure_unlocked(&mut self) -> Result<()> {
        if !self.vault.exists() {
            return Err(anyhow::anyhow!(
                "No vault found. Run 'portkey init' to create one."
            ));
        }

        if !self.vault.is_unlocked() {
            // Try to unlock with no password first (for unencrypted vaults)
            match self.vault.unlock(None) {
                Ok(_) => {
                    println!("Vault unlocked (no password required)!");
                }
                Err(_) => {
                    // Encrypted vault - prompt for password
                    let password = Password::new("Enter master password:")
                        .with_display_toggle_enabled()
                        .prompt()?;

                    self.vault.unlock(Some(&password))?;
                    println!("Vault unlocked!");
                }
            }
        }

        Ok(())
    }

    fn find_server_by_name_or_id(&self, name_or_id: &str) -> Result<&Server> {
        let servers = self.vault.list_servers()?;

        servers
            .iter()
            .find(|s| {
                s.name.eq_ignore_ascii_case(name_or_id) || s.id.to_string().starts_with(name_or_id)
            })
            .ok_or_else(|| anyhow::anyhow!("Server '{}' not found", name_or_id))
    }

    async fn connect_to_server(&self, server: &Server) -> Result<()> {
        ssh::connect(server)
    }
}