cleansh 0.1.2

Sanitize your terminal output. One tool. One purpose.
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
# ๐Ÿงญ Cleansh โ€“ Sanitize Your Terminal Output, Securely.

[![CI](https://github.com/KarmaYama/cleansh/actions/workflows/rust.yml/badge.svg)](https://github.com/KarmaYama/cleansh/actions/workflows/rust.yml)
[![Release](https://github.com/KarmaYama/cleansh/actions/workflows/release.yml/badge.svg)](https://github.com/KarmaYama/cleansh/actions/workflows/release.yml)

> A high-trust, single-purpose CLI tool that sanitizes terminal output for safe sharing. Secure by default. Zero config required. Extendable when needed. It is still in active development; while the latest **`v0.1.2`** release addresses critical output formatting and stability, we value your feedback, so please do report any issues you encounter.

-----

## โœจ Overview

`cleansh` is a powerful and reliable command-line utility designed to help you quickly and securely redact sensitive information from your terminal output. Whether you're debugging, collaborating, or sharing logs, `cleansh` ensures that confidential data like IP addresses, email addresses, and access tokens never leave your local environment unmasked. Piped directly from `stdin` or loaded from files, `cleansh` provides a robust, pre-configured solution for data sanitization, with flexible options for custom rules and output formats.

-----

## 1\. โœ… Core Capabilities โ€“ Current Version (**v0.1.2**) - Stability & Output Refinement

This version of `cleansh` focuses on providing essential sanitization features with a strong emphasis on security and ease of use, building upon the "Precision View" of `v0.1.1`. Based on our rigorously passing test suite, you can trust `cleansh` to accurately mask the following sensitive data types and handle output reliably:

### ๐ŸŽฏ Primary Redaction Categories:

  * **Emails:** Common email address formats (e.g., `user@example.com`).
  * **IP Addresses:** Both IPv4 addresses (e.g., `192.168.1.1`).
  * **Tokens & Secrets:** Generic tokens, JSON Web Tokens (JWTs), AWS keys, GCP keys, SSH keys, and common hex secrets.
  * **Absolute Paths:** Linux paths (e.g., `/home/user/documents/report.pdf` are transformed to `~/home/user/...`) and macOS paths (e.g., `/Users/admin/logs/app.log` are transformed to `~/Users/admin/...`).

### ๐Ÿ’ก Optional Features (with flags):

`cleansh` provides command-line flags to customize its behavior, all thoroughly tested:

  * **Copy to Clipboard:** Use `--clipboard` (`-c`) to automatically copy the sanitized output to your system's clipboard.
  * **Show Diff View:** Use `--diff` (`-d`) to display a clear, **line-by-line colored diff** between the original and sanitized content, highlighting all redactions, powered by the `diffy` crate.
  * **Load Custom Config:** Use `--config <path/to/config.yaml>` to apply your own custom redaction rules, which can augment or override the powerful built-in defaults.
  * **Output to File:** Use `--out <path/to/result.txt>` to write the sanitized output directly to a specified file.

-----

## 1.5 ๐Ÿš€ Usage Examples

`cleansh` is designed to integrate seamlessly into your command-line workflow. Here are some common ways to use it:

### Basic Sanitization (Piping from `stdin`)

Pipe the output of any command directly into `cleansh`. The sanitized content will be printed to your terminal.

**Example: Sanitizing a sensitive echo message**

```powershell
# On Windows (PowerShell)
echo "My email is test@example.com and my IP is 192.168.1.1." | .\target\release\cleansh.exe

# On Linux/macOS (Bash/Zsh)
echo "My email is test@example.com and my IP is 192.168.1.1." | ./target/release/cleansh
````

**Example: Cleaning `docker logs` before sharing**

```bash
docker logs my-sensitive-container | cleansh
```

**Example: Sanitizing `kubectl logs` output**

```bash
kubectl logs my-pod-with-secrets | cleansh
```

### Copying to Clipboard (`-c` or `--clipboard`)

Sanitize output and instantly copy the result to your system's clipboard.

```bash
git config --list | cleansh -c
```

### Showing a Diff View (`-d` or `--diff`)

See exactly what `cleansh` changed with a clear, colored diff.

```bash
cat /var/log/app/errors.log | cleansh -d
```

### Loading Custom Redaction Rules (`--config <path>`)

Apply your own specific patterns for redaction by providing a path to a custom YAML configuration file.

```bash
cat my_sensitive_data.txt | cleansh --config /path/to/my_custom_rules.yaml
```

### Outputting to a File (`-o <path>`)

Instead of printing to `stdout`, save the sanitized content directly to a file.

```bash
my-script-with-secrets.sh | cleansh -o safe_output.log
```

### Reading Input from a File

You can also provide a file as input using standard shell redirection.

```bash
cleansh < raw_log_file.txt
```

### Combining Flags

Flags can be combined for powerful workflows. For example, sanitize, show diff, and save to a file:

```bash
my-command-output | cleansh -d -o sanitized_output.txt
```

-----

## 2\. ๐Ÿงฑ Project Structure

The `cleansh` codebase is thoughtfully organized for clarity, modularity, and maintainability, adhering to best practices for Rust projects.

```
cleansh/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.rs                 # CLI entrypoint, argument parsing, high-level orchestration
โ”‚   โ”œโ”€โ”€ commands/
โ”‚   โ”‚   โ””โ”€โ”€ cleansh.rs          # Main CLI logic, handles command execution, config loading, and flag processing
โ”‚   โ”œโ”€โ”€ tools/
โ”‚   โ”‚   โ””โ”€โ”€ sanitize_shell.rs   # Core sanitization engine: contains all regex definitions, redaction logic, and path normalization
โ”‚   โ”œโ”€โ”€ config/                 # (New: Consider this as a module for config handling)
โ”‚   โ”‚   โ””โ”€โ”€ mod.rs              # Logic for loading default and user-defined rules
โ”‚   โ”œโ”€โ”€ ui/                     # (New: Consider this as a module for UI handling)
โ”‚   โ”‚   โ”œโ”€โ”€ mod.rs              # Public UI functions
โ”‚   โ”‚   โ”œโ”€โ”€ output_format.rs    # Handles all terminal output formatting (summaries, diffs, messages)
โ”‚   โ”‚   โ””โ”€โ”€ theme.rs            # Manages color themes and styling
โ”‚   โ””โ”€โ”€ tests/                  # Unit tests for individual components
โ”œโ”€โ”€ config/
โ”‚   โ””โ”€โ”€ default_rules.yaml      # Embedded immutable default redaction rules
โ”œโ”€โ”€ .env                        # Runtime configuration settings (local development)
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ Cargo.toml                  # Rust project manifest
โ”œโ”€โ”€ README.md                   # This file
โ”œโ”€โ”€ LICENSE (MIT)               # MIT License file
```

-----

## 3\. โš™ Configuration Strategy

`cleansh` employs a layered configuration approach, prioritizing security and ease of use.

### 1\. Runtime Settings (from `.env`)

These settings control `cleansh`'s operational behavior and are loaded using `dotenvy` for flexible overrides per deployment environment.

**Example `.env` keys:**

  * `LOG_LEVEL=info` (Controls verbosity of internal logging)
  * `CLIPBOARD_ENABLED=true` (Enables or disables clipboard functionality globally)
  * `DEFAULT_CONFIG=./config/default_rules.yaml` (Specifies the path to default rules)

> This strategy ensures secure, minimal configuration that is easily overridable for different use cases.

### 2\. User Rule Configuration (Optional, via `--config`)

For advanced users, `cleansh` supports loading custom redaction rules from a YAML file specified via the `--config` flag. These rules are parsed with `serde_yaml` and intelligently merged with the built-in default rules.

**Example `custom_rules.yaml`:**

```yaml
rules:
  - name: my_company_id
    pattern: 'EMP-\d{5}'
    replace_with: '[EMPLOYEE_ID_REDACTED]'
    description: "Redacts company employee IDs."
    multiline: false
    dot_matches_new_line: false
  - name: email # Overrides the default email rule
    pattern: '([a-z]+@[a-z]+\.org)' # Only matches .org emails
    replace_with: '[ORG_EMAIL_REDACTED]'
    multiline: false
    dot_matches_new_line: false
```

> As confirmed by our integration tests, custom rules can selectively override default rules, providing granular control over the sanitization process.

-----

## ๐Ÿ“‹ Clipboard Support

When using the `-c` / `--clipboard` flag, `cleansh` will copy sanitized output to your system clipboard.

### โœ”๏ธ Supported by Default:

  - **macOS**
  - **Windows**

### โš ๏ธ Linux Users:

Clipboard support requires one of the following utilities to be installed:

  - `xclip`
  - `xsel`
  - `wl-clipboard`

Without these, clipboard functionality may fail silently or print a warning.

> If you're running `cleansh` in a headless server or container, clipboard features will be disabled automatically.

-----

## 4\. ๐Ÿง  Sanitizer Engine Design (in `src/tools/sanitize_shell.rs`)

The heart of `cleansh` is its robust sanitization engine, designed for efficiency and precision.

### Internal Pipeline:

1.  **Input Acquisition:** Reads content from `stdin` or a specified file.
2.  **Path Normalization:** Transforms absolute paths (e.g., `/Users/alex/...`) into user-friendly tilde-prefixed paths (e.g., `~/...`).
3.  **Built-in Rule Application:** Applies a comprehensive set of immutable default regex rules, embedded directly at compile time for security and performance.
4.  **User Rule Application:** If provided, user-defined YAML rules are dynamically merged and applied, allowing for flexible customization.
5.  **Output & Interaction:** The sanitized content is then routed based on flags: printed to `stdout`, copied to the clipboard, written to a file, or presented in a diff view.

### Engine Architecture:

  * **Efficient Matching:** Utilizes the `regex::RegexSet` for highly optimized, simultaneous matching of multiple regular expressions against the input.
  * **Immutable Defaults:** The core redaction rule-set is compiled directly into the binary, preventing runtime tampering.
  * **ANSI Stripping:** Employs the `strip-ansi-escapes` crate to ensure that sensitive data hidden within ANSI escape codes (common in terminal output) is also properly identified and redacted.

-----

## 5\. ๐Ÿ“Š Logging and Error Handling

`cleansh` is built with a focus on clear operational visibility and resilient error management.

### Logging:

Leverages the `log` crate with `env_logger` to provide detailed insights into its operation.

  * **Levels:** Supports `trace`, `debug`, `info`, `warn`, and `error` levels.
  * **Control:** Log levels can be configured via the `.env` file (`LOG_LEVEL`) or a dedicated CLI flag (e.g., `--debug` for `debug` level).

### Error Handling:

Implements robust error management using `anyhow` for top-level error aggregation and `thiserror` for defining structured, custom error types.

  * All sanitization failures, I/O errors, or configuration issues are:
      * Logged cleanly with relevant context.
      * Designed to be non-fatal where possible, allowing the tool to continue processing if an error is not explicitly blocking.

-----

## 6\. ๐Ÿงช Testing and Validations

A comprehensive testing strategy ensures the reliability and correctness of `cleansh`. Our recent test runs confirm all critical functionalities are working as expected.

### Unit Tests:

  * **Regex Pattern Accuracy:** Thoroughly validate that individual regex patterns correctly identify and redact specific sensitive data types.
  * **Path Normalization Behavior:** Ensures that absolute paths are accurately converted to their tilde-prefixed equivalents.
  * **YAML Parsing Logic:** Confirms the correct loading and interpretation of custom rule YAML files.

### Integration Tests:

  * **Simulated Stdin Piping:** Tests the primary mode of operation by piping various inputs to `cleansh` via `stdin`.
  * **Assert Output Match:** Verifies that the resulting sanitized output precisely matches expected strings for different input scenarios.
  * **Clipboard Behavior (Mocked):** Confirms that the clipboard functionality is correctly invoked and handles data as expected.
  * **File Output Validation:** Tests the `--out` flag, ensuring content is accurately written to the specified file.
  * **Diff View Accuracy:** Asserts that the diff output correctly highlights redactions and **line changes as per the `diffy` crate's output.**
  * **Custom Configuration Application:** Validates that `--config` files are loaded, merged, and correctly apply custom and overridden rules.
  * **No Redaction Scenario:** Ensures `cleansh` behaves gracefully and provides appropriate messages when no sensitive data is found.

-----

## 7\. ๐Ÿš€ Packaging & Distribution

`cleansh` is designed for seamless cross-platform deployment and ease of installation, catering to both Rust developers and general users.

### Installation

#### ๐Ÿ“ฆ Recommended: Prebuilt Cross-Platform Binaries via `cargo-dist`

The easiest way to get `cleansh` for most users is by using our pre-built binaries. These are automatically generated for various operating systems (Windows, macOS, Linux) when a new release is tagged.

**One-line Install (Linux/macOS):**

```bash
curl -sSf [https://cleansh.sh/install.sh](https://cleansh.sh/install.sh) | sh
```

**(Note: `https://cleansh.sh/install.sh` is a placeholder. Update with your actual distribution script URL once available\!)**

#### For Rust Developers: Install from Crates.io

If you have the Rust toolchain installed, you can quickly install `cleansh` directly from [crates.io](https://crates.io/):

```bash
cargo install cleansh
```

To **update** to the latest version, simply run:

```bash
cargo install cleansh --force
```

This is the recommended and most secure way to update for Rust developers, leveraging Cargo's robust package management.

#### Building from Source

To build `cleansh` from its source code, you'll need the Rust toolchain installed.

1.  **Clone the repository:**
    ```bash
    git clone [https://github.com/KarmaYama/cleansh.git](https://github.com/KarmaYama/cleansh.git)
    cd cleansh
    ```
2.  **Build in release mode (recommended for performance):**
    ```bash
    cargo build --release
    ```
    The executable will be located at `target/release/cleansh` (or `cleansh.exe` on Windows).
3.  **Run tests (optional, but recommended):**
    ```bash
    cargo test
    ```

### Distribution Automation

We leverage `cargo-dist` to streamline the release process.
After setting up `cargo-dist` (using `cargo dist init`), you can build distribution archives with:

```bash
cargo dist build
```

This generates packages ready for release to platforms like GitHub Releases.

-----

## 8\. ๐Ÿ“œ Metadata & License

### Metadata (in `Cargo.toml`)

```toml
[package]
name = "cleansh"
version = "0.1.2" # <--- UPDATED to 0.1.2
edition = "2021"
description = "Sanitize your terminal output. One tool. One purpose."
license = "MIT"
repository = "[https://github.com/KarmaYama/cleansh](https://github.com/KarmaYama/cleansh)"
readme = "README.md"
categories = ["command-line-utilities", "security", "productivity", "text-processing"] # Added 'text-processing' for better discoverability
keywords = ["cli", "security", "redact", "sanitize", "clipboard", "privacy", "log-sanitization"] # Expanded keywords for better discoverability
```

### License

`cleansh` is open-source software distributed under the permissive **MIT License**. A full copy of the license is included in the `LICENSE` file within the source repository.

-----

## 9\. ๐Ÿ” Security by Default Principles

`cleansh` is engineered with a "secure by default" mindset, embodying several key security principles:

| Feature                   | Security Principle                                                                                                          |
| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------- |
| No runtime evaluations    | All redaction logic is static and regex-based, preventing arbitrary code execution from external inputs.                      |
| No external network calls | `cleansh` operates entirely locally, with no HTTP/cloud dependencies or telemetry. Your data stays private.                 |
| Immutable default rules   | The core redaction rule-set is embedded at compile time and cannot be altered without recompilation, ensuring integrity.    |
| Path redaction built-in   | Automatically prevents the unintentional leakage of personal filesystem details by normalizing paths.                       |
| YAML sandboxed parsing    | User-defined YAML config files are strictly parsed for declarative rules; no execution capabilities are allowed.              |
| Clipboard output opt-in   | Copying to clipboard is an explicit opt-in action (`-c` flag), not a default, to prevent silent data transfer.              |

-----

## 10\. ๐Ÿ›  Future-Proofing (Post v1.0 Aspirations)

As `cleansh` evolves, we envision expanding its utility and integration capabilities:

  * **Plugin System:** Develop a modular plugin architecture to allow dynamic loading of external redaction logic (e.g., from `/tools/*.rs`).
  * **Integrated Solutions:** Explore creating VS Code extensions or a lightweight web GUI for broader accessibility.
  * **WebAssembly (Wasm) Version:** Compile `cleansh` to WebAssembly for client-side, browser-based log sanitization.
  * **Custom Git Hooks:** Implement pre-commit or post-merge Git hooks to automatically sanitize commit messages or patch diffs before sharing.
  * **Advanced Redaction Tiers:** Investigate features like auto-detection of security tokens from cloud providers and dynamic secrets for enterprise use cases.

-----

## ๐Ÿงต Summary of Technology Stack

| Area              | Stack/Choice                                 |
| :---------------- | :------------------------------------------- |
| Language          | Rust                                         |
| Config Format     | `.env` + Optional YAML                       |
| CLI Parsing       | `clap` with derives                          |
| Regex Engine      | `regex` crate                                |
| ANSI Stripping    | `strip-ansi-escapes`                         |
| Diff Generation   | `diffy`                                      |
| Clipboard         | `arboard`                                    |
| Logging           | `log` + `env_logger`                         |
| Error Handling    | `anyhow` + `thiserror`                       |
| Installation      | `cargo-dist` + curl script / `cargo install` |
| License           | MIT                                          |

-----

```
```