claudy 0.2.2

Modern multi-provider launcher for Claude CLI
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
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::path::Path;

use crate::providers::index::ProviderIndex;

/// Credential store backed by a dotenv-style file.
///
/// Wraps a `HashMap<String, String>` with typed methods for load/save/normalize,
/// keeping the ergonomics of a map via `Deref`/`DerefMut`.
#[derive(Debug, Clone, Default)]
pub struct SecretVault(HashMap<String, String>);

impl SecretVault {
    pub fn empty() -> Self {
        Self(HashMap::new())
    }

    pub fn load_from(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let raw = match std::fs::read(path.as_ref()) {
            Ok(d) => d,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::empty()),
            Err(e) => return Err(e.into()),
        };

        Self::guard_not_symlink(path.as_ref())?;

        raw.split(|&b| b == b'\n')
            .enumerate()
            .filter(|(_, line)| {
                let text = std::str::from_utf8(line).unwrap_or("");
                let trimmed = text.trim();
                !trimmed.is_empty() && !trimmed.starts_with('#')
            })
            .try_fold(Self::empty(), |mut acc, (i, line)| {
                let text = std::str::from_utf8(line)?.trim();
                let (key, raw_val) = text
                    .split_once('=')
                    .ok_or_else(|| anyhow::anyhow!("invalid secrets file line {}", i + 1))?;
                anyhow::ensure!(is_valid_env_key(key), "invalid secrets file line {}", i + 1);
                acc.0.insert(key.to_owned(), decode_shell_value(raw_val)?);
                Ok(acc)
            })
    }

    pub fn persist_to(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
        let p = path.as_ref();
        if let Some(parent) = p.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let body = self
            .0
            .keys()
            .filter(|k| is_valid_env_key(k))
            .collect::<std::collections::BTreeSet<_>>()
            .iter()
            .map(|k| format!("{}={}\n", k, encode_for_shell(&self.0[*k])))
            .collect::<String>();

        super::atomic::write_atomic(&p.to_string_lossy(), body.as_bytes(), 0o600)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o600))?;
        }
        Ok(())
    }

    /// Strip entries that were valid in older versions but are now redundant.
    pub fn prune_outdated(&mut self, catalog: &ProviderIndex) {
        let builtin_keys = catalog.builtin_secret_keys();
        let stale: Vec<String> = self
            .0
            .iter()
            .filter(|(k, v)| is_stale_legacy_entry(k, v, &builtin_keys))
            .map(|(k, _)| k.clone())
            .collect();
        for k in stale {
            self.0.remove(&k);
        }
    }

    fn guard_not_symlink(path: &Path) -> anyhow::Result<()> {
        let meta = std::fs::symlink_metadata(path)?;
        if meta.file_type().is_symlink() {
            anyhow::bail!("secrets file is a symlink: {}", path.display());
        }
        Ok(())
    }
}

// --- Deref/DerefMut so callers can use `.get()`, `.iter()`, etc. ---

impl Deref for SecretVault {
    type Target = HashMap<String, String>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for SecretVault {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl From<HashMap<String, String>> for SecretVault {
    fn from(map: HashMap<String, String>) -> Self {
        Self(map)
    }
}

impl IntoIterator for SecretVault {
    type Item = (String, String);
    type IntoIter = std::collections::hash_map::IntoIter<String, String>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a SecretVault {
    type Item = (&'a String, &'a String);
    type IntoIter = std::collections::hash_map::Iter<'a, String, String>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

// --- Free functions (public API kept for backward compat) ---

pub fn load_vault(path: &str) -> anyhow::Result<SecretVault> {
    SecretVault::load_from(path)
}

pub fn persist_vault(path: &str, secrets: &SecretVault) -> anyhow::Result<()> {
    secrets.persist_to(path)
}

pub fn prune_outdated_entries(secrets: &mut SecretVault, catalog: &ProviderIndex) {
    secrets.prune_outdated(catalog);
}

pub fn redact(value: &str) -> String {
    redact_credential(value)
}

/// Mask a credential for display, showing only first/last 4 chars.
pub fn redact_credential(value: &str) -> String {
    match value.len() {
        0 => String::new(),
        1..=8 => "****".to_owned(),
        _ => format!("{}****{}", &value[..4], &value[value.len() - 4..]),
    }
}

// --- Internal helpers ---

fn is_stale_legacy_entry(
    key: &str,
    val: &str,
    builtin_keys: &std::collections::HashSet<String>,
) -> bool {
    if let Some(suffix) = key.strip_prefix("OPENROUTER_MODEL_") {
        let alias = crate::config::registry::normalize_openrouter_name(
            &suffix.to_lowercase().replace('_', "-"),
        );
        return alias.is_empty() || crate::config::registry::is_launcher_placeholder(val);
    }
    if let Some(rest) = key
        .strip_prefix("CLAUDY_")
        .and_then(|r| r.strip_suffix("_BASE_URL"))
    {
        return builtin_keys.contains(rest);
    }
    false
}

fn is_valid_env_key(key: &str) -> bool {
    let first = key.as_bytes().first();
    first.is_some_and(|&b| {
        (b.is_ascii_uppercase() || b == b'_')
            && key.as_bytes()[1..]
                .iter()
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_')
    })
}

fn decode_shell_value(value: &str) -> anyhow::Result<String> {
    let b = value.as_bytes();
    match b.first() {
        Some(b'\'') if b.last() == Some(&b'\'') && b.len() >= 2 => {
            Ok(value[1..value.len() - 1].to_owned())
        }
        Some(b'$') if b.get(1) == Some(&b'\'') && b.last() == Some(&b'\'') => {
            unescape_ansi(&value[2..value.len() - 1])
        }
        Some(b'"') if b.last() == Some(&b'"') && b.len() >= 2 => {
            Ok(value[1..value.len() - 1].replace("\\\"", "\""))
        }
        _ => Ok(value.to_owned()),
    }
}

fn unescape_ansi(s: &str) -> anyhow::Result<String> {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.as_bytes().iter().copied().peekable();
    while let Some(b) = chars.next() {
        if b != b'\\' {
            out.push(b as char);
            continue;
        }
        match chars.next() {
            None => anyhow::bail!("unterminated escape"),
            Some(b'n') => out.push('\n'),
            Some(b't') => out.push('\t'),
            Some(b'\\') => out.push('\\'),
            Some(b'\'') => out.push('\''),
            Some(other) => out.push(other as char),
        }
    }
    Ok(out)
}

fn encode_for_shell(value: &str) -> String {
    if value.is_empty() {
        return "''".to_owned();
    }
    let needs_quoting = value
        .as_bytes()
        .iter()
        .any(|b| matches!(b, b'\n' | b'\t' | b'\'' | b'\\' | b' '));
    if !needs_quoting {
        return value.to_owned();
    }
    let escaped = value
        .replace('\\', "\\\\")
        .replace('\n', "\\n")
        .replace('\t', "\\t")
        .replace('\'', "\\'");
    format!("$'{}'", escaped)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::index as providers;

    fn load_catalog() -> providers::ProviderIndex {
        providers::load_index().expect("catalog should load")
    }

    #[test]
    fn test_prune_outdated_drops_invalid_entries() {
        let catalog = load_catalog();
        let mut secrets = SecretVault::from(HashMap::from([
            (
                "OPENROUTER_MODEL_CLAUDY_OR_KIMI_K25".to_string(),
                "claudy-or-kimi-k25".to_string(),
            ),
            (
                "OPENROUTER_MODEL_KIMI_K25".to_string(),
                "moonshotai/kimi-k2.5".to_string(),
            ),
            (
                "CLAUDY_ALIBABA_API_KEY_BASE_URL".to_string(),
                "https://example.com/unused".to_string(),
            ),
            ("ALIBABA_API_KEY".to_string(), "secret".to_string()),
        ]));

        secrets.prune_outdated(&catalog);

        assert!(
            !secrets.contains_key("OPENROUTER_MODEL_CLAUDY_OR_KIMI_K25"),
            "expected invalid OpenRouter launcher-shaped entry to be removed"
        );
        assert!(
            !secrets.contains_key("CLAUDY_ALIBABA_API_KEY_BASE_URL"),
            "expected builtin provider legacy base URL to be removed"
        );
        assert_eq!(
            secrets.get("OPENROUTER_MODEL_KIMI_K25").map(|s| s.as_str()),
            Some("moonshotai/kimi-k2.5"),
        );
    }

    #[test]
    fn test_redact_short() {
        assert_eq!(redact_credential("ab"), "****");
    }

    #[test]
    fn test_redact_empty() {
        assert_eq!(redact_credential(""), "");
    }

    #[test]
    fn test_redact_long() {
        assert_eq!(redact_credential("abcdefghijklmnop"), "abcd****mnop");
    }

    #[test]
    fn test_decode_single_quotes() {
        assert_eq!(decode_shell_value("'hello world'").unwrap(), "hello world");
    }

    #[test]
    fn test_decode_ansi_dollar_quotes() {
        assert_eq!(
            decode_shell_value("$'hello\\nworld'").unwrap(),
            "hello\nworld"
        );
        assert_eq!(decode_shell_value("$'tab\\there'").unwrap(), "tab\there");
        assert_eq!(
            decode_shell_value("$'back\\\\slash'").unwrap(),
            "back\\slash"
        );
        assert_eq!(decode_shell_value("$'quo\\'te'").unwrap(), "quo'te");
    }

    #[test]
    fn test_decode_double_quotes() {
        assert_eq!(
            decode_shell_value("\"hello \\\"world\\\"\"").unwrap(),
            "hello \"world\""
        );
    }

    #[test]
    fn test_decode_bare() {
        assert_eq!(decode_shell_value("simple123").unwrap(), "simple123");
    }

    #[test]
    fn test_encode_simple() {
        assert_eq!(encode_for_shell("hello"), "hello");
    }

    #[test]
    fn test_encode_empty() {
        assert_eq!(encode_for_shell(""), "''");
    }

    #[test]
    fn test_encode_special() {
        let quoted = encode_for_shell("hello world");
        assert!(
            quoted.starts_with("$'"),
            "expected $'...' for space, got {}",
            quoted
        );
    }

    #[test]
    fn test_is_valid_env_key() {
        assert!(is_valid_env_key("VALID_KEY"));
        assert!(is_valid_env_key("_LEADING"));
        assert!(!is_valid_env_key(""));
        assert!(!is_valid_env_key("lowercase"));
        assert!(!is_valid_env_key("1STARTS_NUM"));
        assert!(is_valid_env_key("HAS_123"));
        assert!(!is_valid_env_key("HAS-DASH"));
    }

    #[test]
    fn test_roundtrip_via_impl_methods() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("secrets.env");

        let secrets = SecretVault::from(HashMap::from([
            ("MY_KEY".to_string(), "my-value".to_string()),
            ("OTHER_KEY".to_string(), "other".to_string()),
        ]));

        secrets.persist_to(&path).expect("persist");
        let loaded = SecretVault::load_from(&path).expect("load");

        assert_eq!(loaded.get("MY_KEY").map(|s| s.as_str()), Some("my-value"));
        assert_eq!(loaded.get("OTHER_KEY").map(|s| s.as_str()), Some("other"));
    }

    #[test]
    fn test_load_missing_returns_empty() {
        let secrets =
            SecretVault::load_from("/nonexistent/path/secrets.env").expect("load missing");
        assert!(secrets.is_empty());
    }

    #[test]
    fn test_roundtrip_with_special_chars() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("secrets.env");

        let secrets = SecretVault::from(HashMap::from([(
            "MY_KEY".to_string(),
            "value with spaces\nand newlines".to_string(),
        )]));

        secrets.persist_to(&path).expect("persist");
        let loaded = SecretVault::load_from(&path).expect("load");

        assert_eq!(
            loaded.get("MY_KEY").map(|s| s.as_str()),
            Some("value with spaces\nand newlines")
        );
    }
}