tirith 0.3.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Install `eval "$(tirith init)"` into the user's shell profile.
//!
//! Manages a BEGIN/END marker block in `~/.zshrc`, `~/.bashrc`,
//! `~/.config/fish/config.fish`, `~/.config/nushell/config.nu`, or the
//! PowerShell profile so the hook can be installed idempotently and
//! updated or removed without corrupting user content.

use std::fs;
use std::path::PathBuf;

const BEGIN_MARKER: &str = "# BEGIN tirith-hook v1";
const END_MARKER: &str = "# END tirith-hook";
const BEGIN_PREFIX: &str = "# BEGIN tirith-hook";

/// Check whether a binary path needs quoting for shell interpolation.
fn needs_quoting(s: &str) -> bool {
    s.bytes().any(|b| {
        matches!(
            b,
            b' ' | b'\''
                | b'"'
                | b'\t'
                | b'\n'
                | b'\r'
                | b'$'
                | b'\\'
                | b'`'
                | b'('
                | b')'
                | b'!'
                | b'&'
                | b'|'
                | b';'
                | b'<'
                | b'>'
                | b'*'
                | b'?'
                | b'['
                | b']'
                | b'{'
                | b'}'
                | b'~'
        )
    })
}

/// Quote a path for safe interpolation into a shell command.
///
/// Uses single-quote wrapping with per-shell escaping for embedded
/// single quotes. Returns the path unchanged if no special characters.
pub(crate) fn shell_quote(path: &str, shell: &str) -> String {
    if !needs_quoting(path) {
        return path.to_string();
    }
    match shell {
        // PowerShell: single quotes, double a literal ' to escape
        "powershell" => format!("'{}'", path.replace('\'', "''")),
        // POSIX (bash/zsh) and fish: single quotes, break out for literal '
        _ => format!("'{}'", path.replace('\'', "'\\''")),
    }
}

/// Detect the user's default shell and return its profile file path.
fn detect_shell_profile() -> Option<(&'static str, PathBuf)> {
    let home = home::home_dir()?;
    let shell = crate::cli::init::detect_shell();

    let profile = match shell {
        "zsh" => home.join(".zshrc"),
        "bash" => {
            // .bashrc preferred; fall back to .bash_profile, else create .bashrc.
            let bashrc = home.join(".bashrc");
            let bash_profile = home.join(".bash_profile");
            if bashrc.exists() {
                bashrc
            } else if bash_profile.exists() {
                bash_profile
            } else {
                bashrc
            }
        }
        "fish" => home.join(".config").join("fish").join("config.fish"),
        "nushell" => {
            let config = home.join(".config").join("nushell").join("config.nu");
            // Only offer if the user already has a nushell config directory.
            if config.exists() || config.parent().map(|p| p.exists()).unwrap_or(false) {
                config
            } else {
                return None;
            }
        }
        "powershell" => {
            // On macOS/Linux, PowerShell profile lives under ~/.config/powershell/.
            let profile = home
                .join(".config")
                .join("powershell")
                .join("Microsoft.PowerShell_profile.ps1");
            if profile.exists() || profile.parent().map(|p| p.exists()).unwrap_or(false) {
                profile
            } else {
                return None;
            }
        }
        _ => return None,
    };

    Some((shell, profile))
}

/// Check for a manually-added tirith init invocation (uncommented executable line).
///
/// Skips comments and empty lines to avoid false positives on documentation
/// like `# TODO: tirith init` or `# removed tirith init`.
fn has_executable_tirith_init(content: &str) -> bool {
    content.lines().any(|line| {
        let trimmed = line.trim();
        if trimmed.starts_with('#') {
            return false;
        }
        if trimmed.is_empty() {
            return false;
        }
        trimmed.contains("tirith init")
    })
}

/// Validate that each BEGIN marker has a matching END marker.
///
/// Returns Err on unbalanced or nested markers so that `remove_hook_blocks`
/// never silently drops trailing user content.
fn validate_marker_pairing(content: &str) -> Result<(), String> {
    let mut in_block = false;
    for line in content.lines() {
        if line.starts_with(BEGIN_PREFIX) {
            if in_block {
                return Err(
                    "corrupted tirith-hook block — nested BEGIN markers, fix manually".to_string(),
                );
            }
            in_block = true;
        } else if line == END_MARKER {
            if !in_block {
                return Err(
                    "corrupted tirith-hook block — END marker without BEGIN, fix manually"
                        .to_string(),
                );
            }
            in_block = false;
        }
    }
    if in_block {
        return Err("corrupted tirith-hook block — missing END marker, fix manually".to_string());
    }
    Ok(())
}

/// Extract the full managed block (BEGIN through END, inclusive) from content.
fn extract_managed_block(content: &str) -> Option<String> {
    let mut in_block = false;
    let mut block_lines = Vec::new();

    for line in content.lines() {
        if line.starts_with(BEGIN_PREFIX) {
            in_block = true;
            block_lines.push(line);
            continue;
        }
        if in_block {
            block_lines.push(line);
            if line == END_MARKER {
                break;
            }
        }
    }

    if block_lines.is_empty() {
        None
    } else {
        let mut out = block_lines.join("\n");
        out.push('\n');
        Some(out)
    }
}

/// Install the tirith shell hook into the user's shell profile.
///
/// Appends a managed block containing the appropriate init line for the
/// detected shell. Idempotent: skips if block already exists with matching
/// content (unless `force`). Reports drift when block content differs.
pub fn install_shell_hook(tirith_bin: &str, force: bool, dry_run: bool) -> Result<(), String> {
    let (shell, profile_path) = detect_shell_profile().ok_or_else(|| {
        "could not detect shell — add eval \"$(tirith init)\" to your shell profile manually"
            .to_string()
    })?;

    let quoted_bin = shell_quote(tirith_bin, shell);
    let hook_line = match shell {
        "fish" => format!("{quoted_bin} init --shell fish | source"),
        "nushell" => {
            // Nushell can't eval dynamically — resolve the source path at setup time.
            match std::process::Command::new(tirith_bin)
                .args(["init", "--shell", "nushell"])
                .output()
            {
                Ok(out) if out.status.success() => {
                    String::from_utf8_lossy(&out.stdout).trim().to_string()
                }
                _ => {
                    return Err(
                        "could not resolve nushell hook path — run `tirith init --shell nushell` \
                         and add the output to your config.nu manually"
                            .to_string(),
                    );
                }
            }
        }
        "powershell" => {
            format!("Invoke-Expression (& {quoted_bin} init --shell powershell)")
        }
        _ => format!("eval \"$({quoted_bin} init)\""),
    };

    let managed_block = format!("{BEGIN_MARKER}\n{hook_line}\n{END_MARKER}\n");

    let existing = if profile_path.exists() {
        fs::read_to_string(&profile_path)
            .map_err(|e| format!("read {}: {e}", profile_path.display()))?
    } else {
        String::new()
    };

    let begin_count = existing
        .lines()
        .filter(|line| line.starts_with(BEGIN_PREFIX))
        .count();

    // If the user manually added `tirith init` (no managed block), don't
    // touch their profile — they opted out of the managed setup.
    if begin_count == 0 && has_executable_tirith_init(&existing) {
        eprintln!(
            "tirith: shell hook already in {} (manually added), skipping",
            profile_path.display()
        );
        return Ok(());
    }

    validate_marker_pairing(&existing)?;

    match begin_count {
        0 => {
            if dry_run {
                eprintln!(
                    "[dry-run] would append tirith shell hook to {}",
                    profile_path.display()
                );
                return Ok(());
            }

            let mut content = existing;
            if !content.is_empty() && !content.ends_with('\n') {
                content.push('\n');
            }
            if !content.is_empty() {
                content.push('\n');
            }
            content.push_str(&managed_block);

            super::fs_helpers::atomic_write(&profile_path, &content, 0o644)?;
            eprintln!("tirith: added shell hook to {}", profile_path.display());
        }
        1 => {
            let existing_block = extract_managed_block(&existing);
            let matches = existing_block
                .as_deref()
                .map(|b| b == managed_block)
                .unwrap_or(false);

            if matches && !force {
                eprintln!(
                    "tirith: shell hook already in {}, up to date",
                    profile_path.display()
                );
                return Ok(());
            }

            if !matches && !force {
                return Err(format!(
                    "shell hook in {} has different content than expected — use --force to update",
                    profile_path.display()
                ));
            }

            if dry_run {
                eprintln!(
                    "[dry-run] would replace tirith shell hook in {}",
                    profile_path.display()
                );
                return Ok(());
            }

            let cleaned = remove_hook_blocks(&existing);
            let mut content = cleaned;
            if !content.is_empty() && !content.ends_with('\n') {
                content.push('\n');
            }
            content.push('\n');
            content.push_str(&managed_block);

            super::fs_helpers::atomic_write(&profile_path, &content, 0o644)?;
            eprintln!("tirith: replaced shell hook in {}", profile_path.display());
        }
        _ => {
            if !force {
                return Err(format!(
                    "multiple tirith-hook blocks found in {} — use --force to deduplicate",
                    profile_path.display()
                ));
            }
            if dry_run {
                eprintln!(
                    "[dry-run] would deduplicate tirith-hook blocks in {}",
                    profile_path.display()
                );
                return Ok(());
            }

            let cleaned = remove_hook_blocks(&existing);
            let mut content = cleaned;
            if !content.is_empty() && !content.ends_with('\n') {
                content.push('\n');
            }
            content.push('\n');
            content.push_str(&managed_block);

            super::fs_helpers::atomic_write(&profile_path, &content, 0o644)?;
            eprintln!(
                "tirith: deduplicated tirith-hook blocks in {}",
                profile_path.display()
            );
        }
    }

    Ok(())
}

/// Remove all lines between BEGIN and END tirith-hook markers (inclusive).
///
/// SAFETY: Caller must call `validate_marker_pairing` first. This function
/// does not re-validate; if markers are unbalanced it will drop trailing
/// content (which is why the validation gate exists).
fn remove_hook_blocks(content: &str) -> String {
    let mut result = Vec::new();
    let mut suppressing = false;

    for line in content.lines() {
        if line.starts_with(BEGIN_PREFIX) {
            suppressing = true;
            continue;
        }
        if line == END_MARKER {
            suppressing = false;
            continue;
        }
        if !suppressing {
            result.push(line);
        }
    }

    let mut out = result.join("\n");
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

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

    #[test]
    fn quote_simple_name_unchanged() {
        assert_eq!(shell_quote("tirith", "zsh"), "tirith");
        assert_eq!(shell_quote("tirith", "fish"), "tirith");
        assert_eq!(shell_quote("tirith", "powershell"), "tirith");
    }

    #[test]
    fn quote_path_with_spaces_posix() {
        assert_eq!(
            shell_quote("/usr/local/my apps/tirith", "zsh"),
            "'/usr/local/my apps/tirith'"
        );
        assert_eq!(
            shell_quote("/usr/local/my apps/tirith", "bash"),
            "'/usr/local/my apps/tirith'"
        );
    }

    #[test]
    fn quote_path_with_spaces_fish() {
        assert_eq!(
            shell_quote("/usr/local/my apps/tirith", "fish"),
            "'/usr/local/my apps/tirith'"
        );
    }

    #[test]
    fn quote_path_with_spaces_powershell() {
        assert_eq!(
            shell_quote("/usr/local/my apps/tirith", "powershell"),
            "'/usr/local/my apps/tirith'"
        );
    }

    #[test]
    fn quote_path_with_single_quote_posix() {
        assert_eq!(
            shell_quote("/opt/it's/tirith", "zsh"),
            "'/opt/it'\\''s/tirith'"
        );
    }

    #[test]
    fn quote_path_with_single_quote_powershell() {
        assert_eq!(
            shell_quote("/opt/it's/tirith", "powershell"),
            "'/opt/it''s/tirith'"
        );
    }

    #[test]
    fn quote_path_with_dollar_sign() {
        assert_eq!(
            shell_quote("/home/$user/tirith", "bash"),
            "'/home/$user/tirith'"
        );
    }

    #[test]
    fn quote_path_with_redirection_and_glob_chars() {
        assert_eq!(
            shell_quote("/tmp/hook>[abc]?*", "bash"),
            "'/tmp/hook>[abc]?*'"
        );
    }

    #[test]
    fn detects_eval_form() {
        let content = "export PATH=...\neval \"$(tirith init)\"\n";
        assert!(has_executable_tirith_init(content));
    }

    #[test]
    fn detects_fish_form() {
        let content = "set -x PATH ...\ntirith init --shell fish | source\n";
        assert!(has_executable_tirith_init(content));
    }

    #[test]
    fn skips_commented_line() {
        let content = "# eval \"$(tirith init)\"\n# TODO: add tirith init\n";
        assert!(!has_executable_tirith_init(content));
    }

    #[test]
    fn skips_empty_file() {
        assert!(!has_executable_tirith_init(""));
        assert!(!has_executable_tirith_init("\n\n"));
    }

    #[test]
    fn valid_single_block() {
        let content = "before\n# BEGIN tirith-hook v1\nhook\n# END tirith-hook\nafter\n";
        assert!(validate_marker_pairing(content).is_ok());
    }

    #[test]
    fn valid_no_blocks() {
        assert!(validate_marker_pairing("just content\n").is_ok());
    }

    #[test]
    fn missing_end_marker() {
        let content = "# BEGIN tirith-hook v1\nhook\nno end\n";
        let err = validate_marker_pairing(content).unwrap_err();
        assert!(err.contains("missing END"), "got: {err}");
    }

    #[test]
    fn orphan_end_marker() {
        let content = "stuff\n# END tirith-hook\n";
        let err = validate_marker_pairing(content).unwrap_err();
        assert!(err.contains("END marker without BEGIN"), "got: {err}");
    }

    #[test]
    fn nested_begin_markers() {
        let content = "# BEGIN tirith-hook v1\n# BEGIN tirith-hook v1\n# END tirith-hook\n";
        let err = validate_marker_pairing(content).unwrap_err();
        assert!(err.contains("nested BEGIN"), "got: {err}");
    }

    #[test]
    fn extract_existing_block() {
        let content =
            "before\n# BEGIN tirith-hook v1\neval \"$(tirith init)\"\n# END tirith-hook\nafter\n";
        let block = extract_managed_block(content).unwrap();
        assert_eq!(
            block,
            "# BEGIN tirith-hook v1\neval \"$(tirith init)\"\n# END tirith-hook\n"
        );
    }

    #[test]
    fn extract_no_block() {
        assert!(extract_managed_block("just content\n").is_none());
    }

    #[test]
    fn remove_single_block() {
        let content =
            "before\n# BEGIN tirith-hook v1\neval \"$(tirith init)\"\n# END tirith-hook\nafter\n";
        let result = remove_hook_blocks(content);
        assert_eq!(result, "before\nafter\n");
    }

    #[test]
    fn remove_multiple_blocks() {
        let content = "# BEGIN tirith-hook v1\nline1\n# END tirith-hook\nmiddle\n# BEGIN tirith-hook v1\nline2\n# END tirith-hook\nend\n";
        let result = remove_hook_blocks(content);
        assert_eq!(result, "middle\nend\n");
    }

    #[test]
    fn remove_no_blocks() {
        let content = "just content\nno hook\n";
        let result = remove_hook_blocks(content);
        assert_eq!(result, "just content\nno hook\n");
    }

    #[test]
    fn remove_preserves_surrounding_content() {
        let content = "export FOO=bar\n# BEGIN tirith-hook v1\neval stuff\n# END tirith-hook\nexport BAZ=qux\n";
        let result = remove_hook_blocks(content);
        assert_eq!(result, "export FOO=bar\nexport BAZ=qux\n");
    }

    #[test]
    fn end_marker_exact_match_only() {
        // "# END tirith-hooking" is a prefix match but NOT equal to the END
        // marker, so it stays inside the block and gets removed with it.
        let content =
            "# BEGIN tirith-hook v1\nhook\n# END tirith-hooking\nstuff\n# END tirith-hook\n";
        let result = remove_hook_blocks(content);
        assert_eq!(result, "");
    }

    #[test]
    fn drift_detected_when_content_differs() {
        let existing_block =
            "# BEGIN tirith-hook v1\neval \"$(old-tirith init)\"\n# END tirith-hook\n";
        let new_block = "# BEGIN tirith-hook v1\neval \"$(tirith init)\"\n# END tirith-hook\n";
        assert_ne!(existing_block, new_block);
    }
}