1use anyhow::{Context, Result};
9use std::collections::HashMap;
10use std::io::{self, BufRead, Read};
11use std::path::PathBuf;
12
13use crate::core::crypto::decrypt;
14use crate::core::init::Locker;
15use crate::core::store::SecretsStore;
16
17const PASSPHRASE_ENV_VAR: &str = "LAZY_LOCKER_PASSPHRASE";
19
20pub fn get_passphrase(arg_passphrase: Option<&str>) -> Result<String> {
23 if let Some(pass) = arg_passphrase {
24 return Ok(pass.to_string());
25 }
26
27 std::env::var(PASSPHRASE_ENV_VAR).context(format!(
28 "Passphrase required. Use --passphrase <PASS> or set {} environment variable",
29 PASSPHRASE_ENV_VAR
30 ))
31}
32
33#[derive(Debug, Clone, Copy, PartialEq)]
35pub enum OutputFormat {
36 Human,
37 Json,
38 Env,
39}
40
41impl OutputFormat {
42 pub fn from_args(json: bool, env: bool) -> Self {
43 if json {
44 OutputFormat::Json
45 } else if env {
46 OutputFormat::Env
47 } else {
48 OutputFormat::Human
49 }
50 }
51}
52
53pub fn cmd_init(passphrase: &str, force: bool) -> Result<()> {
59 let locker_dir = get_locker_dir()?;
60 let salt_path = locker_dir.join("salt");
61
62 if salt_path.exists() && !force {
63 anyhow::bail!(
64 "Locker already exists at {:?}. Use --force to overwrite.",
65 locker_dir
66 );
67 }
68
69 if force && salt_path.exists() {
70 std::fs::remove_file(locker_dir.join("salt")).ok();
72 std::fs::remove_file(locker_dir.join("hash")).ok();
73 std::fs::remove_file(locker_dir.join("secrets.json")).ok();
74 }
75
76 let _locker = Locker::init_or_load_with_passphrase(passphrase)?;
78
79 println!("✅ Locker initialized at {:?}", locker_dir);
80 Ok(())
81}
82
83pub fn cmd_token_add(
89 name: &str,
90 value: Option<&str>,
91 stdin: bool,
92 expires_days: Option<u32>,
93 passphrase: &str,
94) -> Result<()> {
95 let secret_value = if stdin {
96 read_value_from_stdin()?
97 } else if let Some(v) = value {
98 v.to_string()
99 } else {
100 anyhow::bail!("Value required. Provide as argument or use --stdin");
101 };
102
103 let locker = Locker::init_or_load_with_passphrase(passphrase)?;
104 let key = locker.get_key().context("Failed to get encryption key")?;
105 let locker_dir = locker.base_dir().clone();
106
107 let mut store = SecretsStore::load(&locker_dir, key)?;
108 store.add_secret(
109 name.to_string(),
110 secret_value,
111 expires_days,
112 &locker_dir,
113 key,
114 )?;
115
116 println!("✅ Token '{}' added", name);
117 if let Some(days) = expires_days {
118 println!(" Expires in {} days", days);
119 }
120
121 Ok(())
122}
123
124pub fn cmd_token_get(name: &str, format: OutputFormat, passphrase: &str) -> Result<()> {
126 let locker = Locker::init_or_load_with_passphrase(passphrase)?;
127 let key = locker.get_key().context("Failed to get encryption key")?;
128 let locker_dir = locker.base_dir().clone();
129
130 let store = SecretsStore::load(&locker_dir, key)?;
131 let secret = store
132 .get_secret(name)
133 .context(format!("Token '{}' not found", name))?;
134
135 if secret.is_expired() {
136 anyhow::bail!("Token '{}' has expired", name);
137 }
138
139 let value = decrypt(&secret.encrypted_value, key)?;
140 let value_str = String::from_utf8(value)?;
141
142 match format {
143 OutputFormat::Human => println!("{}", value_str),
144 OutputFormat::Json => {
145 let obj = serde_json::json!({
146 "name": name,
147 "value": value_str,
148 "expires_at": secret.expires_at,
149 });
150 println!("{}", serde_json::to_string_pretty(&obj)?);
151 }
152 OutputFormat::Env => println!("{}={}", name, value_str),
153 }
154
155 Ok(())
156}
157
158pub fn cmd_token_list(format: OutputFormat, passphrase: &str) -> Result<()> {
160 let locker = Locker::init_or_load_with_passphrase(passphrase)?;
161 let key = locker.get_key().context("Failed to get encryption key")?;
162 let locker_dir = locker.base_dir().clone();
163
164 let store = SecretsStore::load(&locker_dir, key)?;
165 let secrets = store.list_secrets();
166
167 match format {
168 OutputFormat::Human => {
169 if secrets.is_empty() {
170 println!("No tokens found.");
171 return Ok(());
172 }
173
174 println!("{:<30} {:<20} STATUS", "NAME", "EXPIRES");
175 println!("{:-<60}", "");
176
177 for secret in secrets {
178 let status = if secret.is_expired() {
179 "⚠️ EXPIRED"
180 } else {
181 "✓"
182 };
183 println!(
184 "{:<30} {:<20} {}",
185 secret.name,
186 secret.expiration_display(),
187 status
188 );
189 }
190 }
191 OutputFormat::Json => {
192 let list: Vec<_> = secrets
193 .iter()
194 .map(|s| {
195 serde_json::json!({
196 "name": s.name,
197 "expires_at": s.expires_at,
198 "is_expired": s.is_expired(),
199 "days_remaining": s.days_until_expiration(),
200 })
201 })
202 .collect();
203 println!("{}", serde_json::to_string_pretty(&list)?);
204 }
205 OutputFormat::Env => {
206 for secret in secrets {
208 if !secret.is_expired() {
209 let value = decrypt(&secret.encrypted_value, key)?;
210 let value_str = String::from_utf8(value)?;
211 println!("{}={}", secret.name, value_str);
212 }
213 }
214 }
215 }
216
217 Ok(())
218}
219
220pub fn cmd_token_remove(name: &str, passphrase: &str) -> Result<()> {
222 let locker = Locker::init_or_load_with_passphrase(passphrase)?;
223 let key = locker.get_key().context("Failed to get encryption key")?;
224 let locker_dir = locker.base_dir().clone();
225
226 let mut store = SecretsStore::load(&locker_dir, key)?;
227
228 if store.get_secret(name).is_none() {
229 anyhow::bail!("Token '{}' not found", name);
230 }
231
232 store.delete_secret(name, &locker_dir, key)?;
233 println!("✅ Token '{}' removed", name);
234
235 Ok(())
236}
237
238pub fn cmd_import(
244 file: Option<&str>,
245 stdin: bool,
246 format: &str,
247 expires_days: Option<u32>,
248 passphrase: &str,
249) -> Result<()> {
250 let content = if stdin {
251 let mut buf = String::new();
252 io::stdin().read_to_string(&mut buf)?;
253 buf
254 } else if let Some(path) = file {
255 std::fs::read_to_string(path).context(format!("Failed to read file: {}", path))?
256 } else {
257 anyhow::bail!("Provide a file path or use --stdin");
258 };
259
260 let secrets = match format {
261 "env" => parse_env_format(&content)?,
262 "json" => parse_json_format(&content)?,
263 _ => anyhow::bail!("Unknown format: {}. Supported: env, json", format),
264 };
265
266 if secrets.is_empty() {
267 println!("⚠️ No secrets found in input");
268 return Ok(());
269 }
270
271 let locker = Locker::init_or_load_with_passphrase(passphrase)?;
272 let key = locker.get_key().context("Failed to get encryption key")?;
273 let locker_dir = locker.base_dir().clone();
274
275 let mut store = SecretsStore::load(&locker_dir, key)?;
276 let mut count = 0;
277
278 for (name, value) in secrets {
279 store.add_secret(name.clone(), value, expires_days, &locker_dir, key)?;
280 count += 1;
281 }
282
283 println!("✅ Imported {} tokens", count);
284 if let Some(days) = expires_days {
285 println!(" All tokens expire in {} days", days);
286 }
287
288 Ok(())
289}
290
291pub fn cmd_export(format: OutputFormat, passphrase: &str) -> Result<()> {
297 cmd_token_list(format, passphrase)
299}
300
301fn get_locker_dir() -> Result<PathBuf> {
306 use directories::BaseDirs;
307
308 let base_dirs = BaseDirs::new().context("Unable to determine user directories")?;
309 let config_dir = base_dirs.config_dir();
310
311 #[cfg(unix)]
312 let sub_dir = ".lazy-locker";
313 #[cfg(not(unix))]
314 let sub_dir = "lazy-locker";
315
316 let locker_dir = config_dir.join(sub_dir);
317 std::fs::create_dir_all(&locker_dir)?;
318
319 Ok(locker_dir)
320}
321
322fn read_value_from_stdin() -> Result<String> {
323 let stdin = io::stdin();
324 let mut value = String::new();
325
326 stdin.lock().read_line(&mut value)?;
328
329 if value.ends_with('\n') {
331 value.pop();
332 }
333 if value.ends_with('\r') {
334 value.pop();
335 }
336
337 if value.is_empty() {
338 anyhow::bail!("No value provided on stdin");
339 }
340
341 Ok(value)
342}
343
344fn parse_env_format(content: &str) -> Result<HashMap<String, String>> {
345 let mut secrets = HashMap::new();
346
347 for line in content.lines() {
348 let line = line.trim();
349
350 if line.is_empty() || line.starts_with('#') {
352 continue;
353 }
354
355 if let Some(eq_pos) = line.find('=') {
357 let key = line[..eq_pos].trim().to_string();
358 let mut value = line[eq_pos + 1..].trim().to_string();
359
360 if (value.starts_with('"') && value.ends_with('"'))
362 || (value.starts_with('\'') && value.ends_with('\''))
363 {
364 value = value[1..value.len() - 1].to_string();
365 }
366
367 if !key.is_empty() {
368 secrets.insert(key, value);
369 }
370 }
371 }
372
373 Ok(secrets)
374}
375
376fn parse_json_format(content: &str) -> Result<HashMap<String, String>> {
377 let json: serde_json::Value = serde_json::from_str(content)?;
379 let mut secrets = HashMap::new();
380
381 match json {
382 serde_json::Value::Object(obj) => {
383 for (key, value) in obj {
384 if let Some(v) = value.as_str() {
385 secrets.insert(key, v.to_string());
386 }
387 }
388 }
389 serde_json::Value::Array(arr) => {
390 for item in arr {
391 if let (Some(name), Some(value)) = (
392 item.get("name").and_then(|v| v.as_str()),
393 item.get("value").and_then(|v| v.as_str()),
394 ) {
395 secrets.insert(name.to_string(), value.to_string());
396 }
397 }
398 }
399 _ => anyhow::bail!("JSON must be an object or array"),
400 }
401
402 Ok(secrets)
403}
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn test_parse_env_format() {
411 let content = r#"
412# Comment
413DATABASE_URL=postgres://localhost/db
414API_KEY="sk-123456"
415SECRET='my_secret'
416EMPTY=
417
418SPACES = value with spaces
419"#;
420
421 let secrets = parse_env_format(content).unwrap();
422
423 assert_eq!(
424 secrets.get("DATABASE_URL"),
425 Some(&"postgres://localhost/db".to_string())
426 );
427 assert_eq!(secrets.get("API_KEY"), Some(&"sk-123456".to_string()));
428 assert_eq!(secrets.get("SECRET"), Some(&"my_secret".to_string()));
429 assert_eq!(secrets.get("EMPTY"), Some(&"".to_string()));
430 assert_eq!(
431 secrets.get("SPACES"),
432 Some(&"value with spaces".to_string())
433 );
434 }
435
436 #[test]
437 fn test_parse_json_object_format() {
438 let content = r#"{"API_KEY": "sk-123", "DB_URL": "postgres://localhost"}"#;
439
440 let secrets = parse_json_format(content).unwrap();
441
442 assert_eq!(secrets.get("API_KEY"), Some(&"sk-123".to_string()));
443 assert_eq!(
444 secrets.get("DB_URL"),
445 Some(&"postgres://localhost".to_string())
446 );
447 }
448
449 #[test]
450 fn test_parse_json_array_format() {
451 let content = r#"[
452 {"name": "API_KEY", "value": "sk-123"},
453 {"name": "DB_URL", "value": "postgres://localhost"}
454 ]"#;
455
456 let secrets = parse_json_format(content).unwrap();
457
458 assert_eq!(secrets.get("API_KEY"), Some(&"sk-123".to_string()));
459 assert_eq!(
460 secrets.get("DB_URL"),
461 Some(&"postgres://localhost".to_string())
462 );
463 }
464
465 #[test]
466 fn test_output_format_from_args() {
467 assert_eq!(OutputFormat::from_args(false, false), OutputFormat::Human);
468 assert_eq!(OutputFormat::from_args(true, false), OutputFormat::Json);
469 assert_eq!(OutputFormat::from_args(false, true), OutputFormat::Env);
470 assert_eq!(OutputFormat::from_args(true, true), OutputFormat::Json);
472 }
473}