coding-agent-search 0.5.2

Unified TUI search over local coding agent histories
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
//! Client-side encryption for HTML exports.
//!
//! Uses Web Crypto API compatible encryption (AES-GCM) with PBKDF2 key derivation.
//! The encryption happens in Rust, decryption happens in the browser via JavaScript.

#[cfg(feature = "encryption")]
use std::num::NonZeroU32;
#[cfg(feature = "encryption")]
use std::time::Instant;

use serde::Serialize;
use tracing::{debug, warn};

#[cfg(feature = "encryption")]
use tracing::info;
/// Errors that can occur during encryption.
#[derive(Debug, thiserror::Error)]
pub enum EncryptionError {
    /// Key derivation failed
    #[error("key derivation failed: {0}")]
    KeyDerivation(String),
    /// Encryption operation failed
    #[error("encryption failed: {0}")]
    EncryptionFailed(String),
    /// Invalid passphrase
    #[error("invalid passphrase")]
    InvalidPassphrase,
}

/// Encrypted content bundle ready for embedding in HTML.
#[derive(Debug, Clone, Serialize)]
pub struct EncryptedContent {
    /// Base64-encoded salt (16 bytes)
    pub salt: String,
    /// Base64-encoded IV/nonce (12 bytes for AES-GCM)
    pub iv: String,
    /// Base64-encoded ciphertext (includes GCM tag)
    pub ciphertext: String,
    /// PBKDF2 iteration count used for key derivation
    pub iterations: u32,
}

impl EncryptedContent {
    /// Convert to JSON for embedding in HTML.
    ///
    /// Note: Values are expected to be base64-encoded (safe characters only).
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
    }
}

/// Encryption parameters matching Web Crypto API defaults.
#[derive(Debug, Clone)]
pub struct EncryptionParams {
    /// PBKDF2 iterations (600,000 recommended)
    pub iterations: u32,
    /// Salt length in bytes
    pub salt_len: usize,
    /// IV/nonce length in bytes (12 for AES-GCM)
    pub iv_len: usize,
}

impl Default for EncryptionParams {
    fn default() -> Self {
        Self {
            iterations: 600_000,
            salt_len: 16,
            iv_len: 12,
        }
    }
}

/// Encrypt content for client-side decryption.
///
/// This uses AES-256-GCM with PBKDF2-SHA256 key derivation,
/// matching the Web Crypto API implementation in scripts.rs.
///
/// # Note
/// This is the production encryption path for feature-enabled HTML export.
/// It intentionally uses the same algorithm and parameter contract as the
/// browser-side Web Crypto decryptor so exported pages can be decrypted
/// client-side without a server round-trip.
#[cfg(feature = "encryption")]
pub fn encrypt_content(
    plaintext: &str,
    password: &str,
    params: &EncryptionParams,
) -> Result<EncryptedContent, EncryptionError> {
    use aes_gcm::{
        Aes256Gcm, Nonce,
        aead::{Aead, KeyInit},
    };
    use ring::pbkdf2;

    if password.is_empty() {
        warn!(
            component = "encryption",
            operation = "validate_password",
            "Rejected empty password"
        );
        return Err(EncryptionError::InvalidPassphrase);
    }
    if params.iterations == 0 {
        return Err(EncryptionError::KeyDerivation(
            "iterations must be greater than zero".to_string(),
        ));
    }
    if params.salt_len == 0 {
        return Err(EncryptionError::KeyDerivation(
            "salt length must be greater than zero".to_string(),
        ));
    }
    if params.iv_len != 12 {
        return Err(EncryptionError::KeyDerivation(
            "iv length must be 12 bytes for AES-GCM".to_string(),
        ));
    }

    let started = Instant::now();
    info!(
        component = "encryption",
        operation = "encrypt_payload",
        plaintext_bytes = plaintext.len(),
        iterations = params.iterations,
        salt_len = params.salt_len,
        iv_len = params.iv_len,
        "Starting encryption"
    );

    // Generate random salt and IV
    let mut salt = vec![0u8; params.salt_len];
    let mut iv = vec![0u8; params.iv_len];
    fill_encryption_random("salt", &mut salt);
    fill_encryption_random("iv", &mut iv);

    let derive_started = Instant::now();
    // Derive key using PBKDF2-SHA256
    let mut key = zeroize::Zeroizing::new([0u8; 32]); // 256 bits for AES-256
    let iterations = NonZeroU32::new(params.iterations).ok_or_else(|| {
        EncryptionError::KeyDerivation("iterations must be greater than zero".to_string())
    })?;
    pbkdf2::derive(
        pbkdf2::PBKDF2_HMAC_SHA256,
        iterations,
        &salt,
        password.as_bytes(),
        &mut *key,
    );
    debug!(
        component = "encryption",
        operation = "derive_key",
        duration_ms = derive_started.elapsed().as_millis(),
        "Derived key via PBKDF2"
    );

    // Encrypt with AES-256-GCM
    let cipher = Aes256Gcm::new_from_slice(key.as_ref())
        .map_err(|e| EncryptionError::EncryptionFailed(e.to_string()))?;

    let nonce = Nonce::from_slice(&iv);
    let ciphertext = cipher
        .encrypt(nonce, plaintext.as_bytes())
        .map_err(|e| EncryptionError::EncryptionFailed(e.to_string()))?;

    let encrypted = EncryptedContent {
        salt: base64_encode(&salt),
        iv: base64_encode(&iv),
        ciphertext: base64_encode(&ciphertext),
        iterations: params.iterations,
    };

    info!(
        component = "encryption",
        operation = "encrypt_complete",
        ciphertext_bytes = encrypted.ciphertext.len(),
        duration_ms = started.elapsed().as_millis(),
        "Encryption complete"
    );

    Ok(encrypted)
}

/// Fill encryption entropy for salt/IV generation.
#[cfg(feature = "encryption")]
fn fill_encryption_random(label: &str, output: &mut [u8]) {
    if let Some(bytes) = deterministic_test_bytes(label, output.len()) {
        output.copy_from_slice(&bytes);
        return;
    }

    use aes_gcm::aead::{OsRng, rand_core::RngCore};
    OsRng.fill_bytes(output);
}

/// Deterministic bytes for debug/test golden generation only.
#[cfg(feature = "encryption")]
fn deterministic_test_bytes(entropy_label: &str, len: usize) -> Option<Vec<u8>> {
    #[cfg(debug_assertions)]
    {
        let golden_label = dotenvy::var("CASS_HTML_EXPORT_GOLDEN_BYTES_LABEL").ok()?;
        if golden_label.is_empty() {
            return None;
        }

        let mut out = Vec::with_capacity(len);
        let mut counter = 0u64;
        while out.len() < len {
            let mut hasher = blake3::Hasher::new();
            hasher.update(b"cass-html-export-deterministic-encryption-v1");
            hasher.update(golden_label.as_bytes());
            hasher.update(entropy_label.as_bytes());
            hasher.update(&counter.to_le_bytes());
            out.extend_from_slice(hasher.finalize().as_bytes());
            counter += 1;
        }
        out.truncate(len);
        Some(out)
    }

    #[cfg(not(debug_assertions))]
    {
        let _ = (entropy_label, len);
        None
    }
}

/// Placeholder encrypt function when encryption feature is disabled.
#[cfg(not(feature = "encryption"))]
pub fn encrypt_content(
    _plaintext: &str,
    _password: &str,
    _params: &EncryptionParams,
) -> Result<EncryptedContent, EncryptionError> {
    warn!(
        component = "encryption",
        operation = "encrypt_payload",
        "Encryption feature not enabled"
    );
    Err(EncryptionError::EncryptionFailed(
        "encryption feature not enabled - compile with --features encryption".to_string(),
    ))
}

/// Base64 encode bytes (standard alphabet).
#[cfg(feature = "encryption")]
fn base64_encode(data: &[u8]) -> String {
    use base64::Engine;
    base64::prelude::BASE64_STANDARD.encode(data)
}

/// Generate HTML for encrypted content display.
///
/// The JSON is HTML-escaped to prevent XSS even if EncryptedContent
/// contains unexpected data (defensive programming).
pub fn render_encrypted_placeholder(encrypted: &EncryptedContent) -> String {
    debug!(
        component = "encryption",
        operation = "render_placeholder",
        ciphertext_bytes = encrypted.ciphertext.len(),
        "Rendering encrypted placeholder"
    );
    // HTML-escape the JSON to prevent XSS if someone passes malicious data
    let json = encrypted.to_json();
    let escaped_json = html_escape_for_content(&json);
    format!(
        r###"            <!-- Encrypted content - requires password to decrypt -->
            <div id="encrypted-content" hidden>{}</div>
            <div class="encrypted-notice">
                <p>This conversation is encrypted. Enter the password above to view.</p>
            </div>"###,
        escaped_json
    )
}

/// Escape HTML special characters for safe embedding in HTML content.
fn html_escape_for_content(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => result.push_str("&amp;"),
            '<' => result.push_str("&lt;"),
            '>' => result.push_str("&gt;"),
            _ => result.push(c),
        }
    }
    result
}

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

    #[test]
    fn test_encryption_error_display_strings() {
        assert_eq!(
            EncryptionError::KeyDerivation("bad params".to_string()).to_string(),
            "key derivation failed: bad params"
        );
        assert_eq!(
            EncryptionError::EncryptionFailed("cipher failed".to_string()).to_string(),
            "encryption failed: cipher failed"
        );
        assert_eq!(
            EncryptionError::InvalidPassphrase.to_string(),
            "invalid passphrase"
        );
    }

    #[test]
    #[cfg(feature = "encryption")]
    fn test_base64_encode() {
        assert_eq!(base64_encode(b"" as &[u8]), "");
        assert_eq!(base64_encode(b"f" as &[u8]), "Zg==");
        assert_eq!(base64_encode(b"fo" as &[u8]), "Zm8=");
        assert_eq!(base64_encode(b"foo" as &[u8]), "Zm9v");
        assert_eq!(base64_encode(b"foob" as &[u8]), "Zm9vYg==");
        assert_eq!(base64_encode(b"fooba" as &[u8]), "Zm9vYmE=");
        assert_eq!(base64_encode(b"foobar" as &[u8]), "Zm9vYmFy");
    }

    #[test]
    fn test_encrypted_content_to_json() {
        let content = EncryptedContent {
            salt: "abc123".to_string(),
            iv: "xyz789".to_string(),
            ciphertext: "encrypted_data".to_string(),
            iterations: 123_456,
        };

        let json = content.to_json();
        assert!(json.contains("\"salt\":\"abc123\""));
        assert!(json.contains("\"iv\":\"xyz789\""));
        assert!(json.contains("\"ciphertext\":\"encrypted_data\""));
        assert!(json.contains("\"iterations\":123456"));
    }

    #[test]
    fn test_encryption_params_default() {
        let params = EncryptionParams::default();
        assert_eq!(params.iterations, 600_000);
        assert_eq!(params.salt_len, 16);
        assert_eq!(params.iv_len, 12);
    }

    #[test]
    #[cfg(feature = "encryption")]
    fn test_encrypt_content_roundtrip() {
        use aes_gcm::{
            Aes256Gcm, Nonce,
            aead::{Aead, KeyInit},
        };
        use base64::Engine; // Required for decode() method
        use base64::prelude::BASE64_STANDARD;
        use ring::pbkdf2;

        let params = EncryptionParams {
            iterations: 1_000,
            salt_len: 16,
            iv_len: 12,
        };
        let plaintext = "Hello 🌍";
        let test_phrase = ["unit", "test", "phrase"].join(" ");

        let encrypted = encrypt_content(plaintext, &test_phrase, &params).expect("encrypt");
        assert_eq!(encrypted.iterations, params.iterations);

        let salt = BASE64_STANDARD
            .decode(encrypted.salt.as_bytes())
            .expect("salt b64");
        let iv = BASE64_STANDARD
            .decode(encrypted.iv.as_bytes())
            .expect("iv b64");
        let ciphertext = BASE64_STANDARD
            .decode(encrypted.ciphertext.as_bytes())
            .expect("ciphertext b64");

        let mut key = [0u8; 32];
        pbkdf2::derive(
            pbkdf2::PBKDF2_HMAC_SHA256,
            NonZeroU32::new(params.iterations).expect("test iterations should be non-zero"),
            &salt,
            test_phrase.as_bytes(),
            &mut key,
        );

        let cipher = Aes256Gcm::new_from_slice(&key).expect("cipher");
        let nonce = Nonce::from_slice(&iv);
        let decrypted = cipher.decrypt(nonce, ciphertext.as_ref()).expect("decrypt");

        assert_eq!(plaintext, String::from_utf8(decrypted).expect("utf8"));
    }

    #[test]
    #[cfg(feature = "encryption")]
    fn test_encrypt_content_produces_authenticated_ciphertext() {
        let params = EncryptionParams {
            iterations: 1_000,
            salt_len: 16,
            iv_len: 12,
        };
        let result = encrypt_content(
            "sensitive data",
            "authenticated encryption fixture",
            &params,
        )
        .expect("feature-enabled encrypt_content should produce ciphertext");

        assert!(!result.salt.is_empty(), "salt must be generated");
        assert!(!result.iv.is_empty(), "iv must be generated");
        assert_ne!(
            result.ciphertext, "sensitive data",
            "ciphertext must differ from plaintext"
        );
        assert!(
            result.ciphertext.len() > "sensitive data".len(),
            "ciphertext should include authenticated-encryption overhead"
        );
        assert_eq!(result.iterations, params.iterations);
    }

    #[test]
    #[cfg(feature = "encryption")]
    fn test_encrypt_rejects_empty_password() {
        let params = EncryptionParams {
            iterations: 1_000,
            salt_len: 16,
            iv_len: 12,
        };
        let result = encrypt_content("hello", "", &params);
        assert!(matches!(result, Err(EncryptionError::InvalidPassphrase)));
    }

    #[test]
    #[cfg(feature = "encryption")]
    fn test_encrypt_rejects_invalid_params() {
        let mut params = EncryptionParams {
            iterations: 1_000,
            salt_len: 16,
            iv_len: 12,
        };

        params.iterations = 0;
        let result = encrypt_content("hello", "pw", &params);
        assert!(matches!(result, Err(EncryptionError::KeyDerivation(_))));

        params.iterations = 1_000;
        params.salt_len = 0;
        let result = encrypt_content("hello", "pw", &params);
        assert!(matches!(result, Err(EncryptionError::KeyDerivation(_))));

        params.salt_len = 16;
        params.iv_len = 8;
        let result = encrypt_content("hello", "pw", &params);
        assert!(matches!(result, Err(EncryptionError::KeyDerivation(_))));
    }

    #[test]
    #[cfg(not(feature = "encryption"))]
    fn test_encrypt_without_feature_returns_error() {
        let phrase = ["disabled", "feature", "phrase"].join(" ");
        let result = encrypt_content("test", &phrase, &EncryptionParams::default());
        assert!(result.is_err());
    }
}